Django过滤查询外键 [英] Django Filter Query Foreign Key

查看:657
本文介绍了Django过滤查询外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力为自己的项目找到正确的查询。
这是一个示例或我的模型:

I'm struggling getting the right query for my project. Here is an example or my model :

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开头的图书获取所有出版商?
谢谢

how do I get publisher from the book class for example I want to get all publisher for all books that have the title starting with 'hello' ? Thank you

推荐答案

如果要获取发布者,则必须从 Publisher开始。这意味着您必须向后查询Book→Publisher关系。这是文档对此的评价:

If you want to get Publishers, you have to start with Publisher. That means you have to query through the Book → Publisher relation backwards. Here's what the docs say about it:

跨越关系的查找


要跨越关系,只需在模型中使用相关字段的字段名称,用双下划线隔开,直到您想要的字段为止

To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want

...

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

To refer to a "reverse" relationship, just use the lowercase name of the model.

查询:

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

这篇关于Django过滤查询外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆