gpt4 book ai didi

django - Django过滤查询外键

转载 作者:行者123 更新时间:2023-12-03 10:54:49 25 4
gpt4 key购买 nike

我正在努力为我的项目获取正确的查询。
这是一个例子或我的模型:

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”开头的书的出版商都为?
谢谢

最佳答案

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

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 - Django过滤查询外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com