我的模型中有这样的设置:
class Author(models.Model):
name = models.CharField(max_length=100)
class Topic(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, null=True, blank=True)
topics = models.ManyToManyField(Topic, null=True, blank=True)
给定一个作者,我想知道他写了哪些主题:
def author_info(request, pk):
author = get_object_or_404(Author, pk=pk)
topics = ????
如果我指定了一个 through 字段,我可以使用它,但是现在 Django 为我创建了 through 字段,并且由于它应该是透明的,所以我宁愿不引用该字段(除非有一个适当的 Django 构造) )。
最佳答案
使用Lookups that span relationships :
topics = Topic.objects.filter(article__authors=author).distinct()
注意:这里必须使用distinct,因为同一主题可以被不同的文章选择。
关于python - 查询没有命名直通字段的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006440/