class Blog(models.Model):
title = model.CharField(max_length=100)
text = TextField()
tags = ManyToManyField(‘Tag’,blank=True)
…
class Tag(models.Model):
tag = models.ChatField(max_length=50, unique=True)
…
我试图找到一种简单的方法来查找具有相同标签的博客。 例如,某个博客有标签“wood”,“desk”,“furniture”。我想找一些至少有一个标签的博客。
答案 0 :(得分:0)
请参阅此处有关如何过滤关系的文档:https://docs.djangoproject.com/en/1.8/topics/db/queries/#lookups-that-span-relationships
要了解如何设置多个过滤器(带有标签'wood'或'desk'或'furniture'的博客),请参阅此处的示例:https://docs.djangoproject.com/en/1.8/topics/db/queries/#spanning-multi-valued-relationships
下面的代码应该可以达到你想要的效果:
blogs = Blog.objects.filter(tags__tag='wood').filter(tags__tag='desk').filter(tags_tag='furniture')