我在 Django 应用程序中有这两个模型:
class Tag(models.Model):
name = models.CharField(max_length=100, blank=False, unique=True)
class Article(models.Model):
title = models.CharField(max_length=100, blank=True, default='')
tags = models.ManyToManyField(Tag, blank=True)
在我看来,我想过滤文章,只获取articles.tags
包含id == 2
标签的文章>/强>。我该怎么做?
我试过了
tags = Tag.objects.filter(pk=2);
articles = Article.objects.filter(len(tags) > 0)
但是我有这个错误 'bool' object is not itterable
。
最佳答案
这是django过滤manytomany的正确方法
articles = Article.objects.filter(tags__in=[2])
或
tags = Tag.objects.filter(pk=2)
articles = Article.objects.filter(tags__in=tags)
关于python - 在 Django 模型中过滤多对多字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086192/