2015-10-20 109 views
0

我曾發佈關於相同問題。但我無法獲得我想知道的。所以,我再次發佈。如何查找Django模型中的對象具有ManyToMany關係

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) 
    … 

我試圖找到一個簡單的方法來找到博客有相同的標籤。 例如,某個博客的標籤爲「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」] 

在這種情況下。我想查找博客至少有一個博客A的標籤[「1」,「2」,「3」]

所以結果必須是[A,B,C,D,E]

我認爲,下面不是解決方案。

blogs = Blog.objects.filter(tags__tag='1').filter(tags__tag='2').filter(tags_tag='f3') 

或者

blogs = Blog.object.filter(tags__tag='1') 
blogs = blogs.filter(tags__tag='2') 
blogs = blogs.filter(tags__tag='3') 

,因爲它可能會令[博客]作爲結果。

回答

5

試試這個:

blogs = Blog.object.filter(tags__tag__in=['1', '2', '3']) 
1

假設你有一個標題 'A' 博客,你想找到類似的博客 'A'

b = Blog.objects.get(title='a') 
b_tags = b.tags.all() 
similar_blogs = Blog.objects.filter(tags__in=b_tags) 
+0

similar_blogs = Blog.objecrs.filter(tags__in博客= b_tags).distinct()。排除(標題= 'a')的 – eachone

相關問題