Django过滤查询外键

34

我正在为我的项目寻找正确的查询语句。这是我的模型的一个例子:

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

    def __unicode__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.title

如何从书籍类中获取出版商?例如,我想获取所有以“hello”开头的书名对应的出版商。

1个回答

57

如果您想获取出版商信息,您需要从Publisher开始。这意味着您需要通过Book→Publisher反向查询关系。以下是文档中对此的说明:

跨越关系的查找

要跨越关系,只需使用跨越模型相关字段的字段名称,用双下划线分隔,直到您获得所需的字段为止

...

要引用“反向”关系,只需使用模型的小写名称即可。

查询语句:

Publisher.objects.filter(book__title__startswith='hello')

1
如果我想查看某个出版商出版的所有书籍怎么办? - Arindam Roychowdhury
6
Book.objects.filter(publisher__name='Some')的意思是筛选出publisher的name为"Some"的所有书籍。 - Pavel Anossov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接