带有相关项目列表的 Django 过滤器模型
对于带有相关标签表的简单书籍模型,我想滤除具有标签列表的书籍:
class Book(models.Model):
name = models.Textfield()
class Tag(models.Model):
value = models.Textfield()
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="tags")
如果我想搜索所有具有“红色”标签和“蓝色”标签的书籍,我不能简单地运行:
Book.objects.filter(Q(tags__value="red") & Q(tags__value="blue"))
因为那试图找到一个具有“蓝色”和“红色”值的不可能的标签。请注意,条件也不正确,因为我正在寻找具有“红色”和“蓝色”标签的书籍;一本只有一本或另一本书不应退还。
For a simple Book model with a related Tag table, I'd like to filter out Books that have a list of tags:
class Book(models.Model):
name = models.Textfield()
class Tag(models.Model):
value = models.Textfield()
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="tags")
If I want to search all Books that have a both a "red" Tag and a "blue" tag, I can't simply run:
Book.objects.filter(Q(tags__value="red") & Q(tags__value="blue"))
because that tries to find an impossible Tag that has both the value "blue" and "red". Note that OR-ing the conditions is not correct either since I'm looking for Books that have both a "red" and a "blue" tag; a Book with just one or the other should not be returned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个,它的目的是获取具有任一标签的书籍的 id,检查两个列表中都有哪些 id,最后查询您需要的书籍。
Try this, it's meant to get the ids of books that have either tag, check which ids are in both lists, and finally query for the books you need.