django orm中的过滤场M2M

发布于 2025-02-12 02:08:48 字数 909 浏览 0 评论 0原文

我的模型:

class Tag(models.Model):
    tag_name = models.CharField(
        'Tag Name',
        max_length=255,
        null=True
    )

class Book(models.Model):
    name = models.CharField(
        'Name',
        max_length=255,
        null=True
    )
    tag = models.ManyToManyField(
        'Tag',
        related_name='tags',
        blank=True
    )

我不会过滤书的模型。在DB中,我有几行:
标签
| id |名称|
| ----- | ------- |
| 1 | tag_1 |
| 2 | tag_2 |
| 3 | tag_3 |


| id |名称|标签|
| ----- | ------- | ------- |
| 1 | book_1 | tag_1 |
| 2 | book_2 | tag_2 |
| 3 | book_3 | tag_3 |
| 4 | book_4 | tag_1,tag_2,tag_3 |
如果我使用tag = tag_1,tag_2的新模型书,我该如何过滤书籍模型,并且我想在书本模型中找到所有带有标签的模型,包括tag_1或tag_2。 我想要这样的QuerySet(对于TAG = TAG_1,TAG_2):

[(id=1, name=book_1), (id=2, name=book_2), (id=4, name=book_4)]

My models:

class Tag(models.Model):
    tag_name = models.CharField(
        'Tag Name',
        max_length=255,
        null=True
    )

class Book(models.Model):
    name = models.CharField(
        'Name',
        max_length=255,
        null=True
    )
    tag = models.ManyToManyField(
        'Tag',
        related_name='tags',
        blank=True
    )

I wont filtering Book's model. In db i have several rows:
Tag
| id | name |
|-----|------|
| 1 |tag_1 |
| 2 |tag_2 |
| 3 |tag_3 |

Book
| id | name | tags |
|-----|-------|------|
| 1 |book_1 |tag_1|
| 2 |book_2 |tag_2|
| 3 |book_3 |tag_3|
| 4 |book_4 |tag_1, tag_2, tag_3|
How can i filtering book models, if i take new model Book with tag=tag_1, tag_2 and i want find in Book models all model with tag include tag_1 or tag_2.
I want get queryset like this(for tag=tag_1, tag_2):

[(id=1, name=book_1), (id=2, name=book_2), (id=4, name=book_4)]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱成瘾 2025-02-19 02:08:48

如果我理解您的问题,您有一个具有tag_1和tag_2标签的book_5,并且您想根据book_5标签过滤书籍。

您可以使用 value_list
您可以将标签QuerySet变成ID列表,然后基于此筛选您的书籍。
所以是:

    book_5 = Book.objects.get(name='book_5')
    has_book_5_tags = Book.objects.filter(tag__id__in=book_5.tag.all().values_list('id',flat=True))

If I understand your question you have a book_5 which has tags of tag_1 and tag_2 and you want to filter books based on book_5 tags.

you can use value_list
you can turn your tags queryset into a list of IDs and then filter you books based on that.
so it would be:

    book_5 = Book.objects.get(name='book_5')
    has_book_5_tags = Book.objects.filter(tag__id__in=book_5.tag.all().values_list('id',flat=True))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文