我发布了同样的问题.但我无法获得我想知道的东西.所以,我再次发帖.
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)
…
Run Code Online (Sandbox Code Playgroud)
我试图找到一种简单的方法来查找具有相同标签的博客.例如,某个博客的标签为"1","2","3".我想找一些至少有一个标签的博客.有这样的对象:
Blog A Object has tag [“1”, ”2”, ”3”]
Blog B Object has tag [“1”, “3”]
Blog C Object has tag [“2”, “3”]
Blog D Object has tag [“1”, “2”]
Blog E Object has tag [“3”, ”4”, ”5”]
Blog F Object has tag [“6”, ”7”, ”8”]
Run Code Online (Sandbox Code Playgroud)
在这种情况下.我想找到Blogs至少有一个Blog A的标签["1","2","3"]
所以结果必须是[A,B,C,D,E]
我想,下面不是解决方案.
blogs = Blog.objects.filter(tags__tag='1').filter(tags__tag='2').filter(tags_tag='f3')
Run Code Online (Sandbox Code Playgroud)
要么
blogs = Blog.object.filter(tags__tag='1')
blogs = blogs.filter(tags__tag='2')
blogs = blogs.filter(tags__tag='3')
Run Code Online (Sandbox Code Playgroud)
因为它可能会使[博客A]成为结果.
试试这个:
blogs = Blog.object.filter(tags__tag__in=['1', '2', '3'])
Run Code Online (Sandbox Code Playgroud)