楷模:
class Car(models.Model):
field1
field2
field3
class CarOptions(models.Model):
car = models.OneToOneField(Car, primary_key=True)
field4
field5
class CarPictures(models.Model):
car = models.ForeignKey(Car)
field6
field7
所以,我需要在一个 sql 查询中获取有关汽车的所有信息。它在文档中是如何写的:
car = get_object_or_404(Car, pk=car_id)
但这是一个奇怪的(它描述为 ForeignKey 关系的“另一面”)poll.choice_set.all
,它不适用于我的代码。一些复制过去的代码,对不起,文档中没有链接:
# Give the Poll a couple of Choices. The create call constructs a new
# choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a poll's choices) which can be accessed via the API.
>>> p = Poll.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
[]
# Create three choices.
>>> p.choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky', votes=0)
<Choice: The sky>
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)
# Choice objects have API access to their related Poll objects.
>>> c.poll
<Poll: What's up?>
# And vice versa: Poll objects get access to Choice objects.
>>> p.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
我没有得到choice_set.all()
。我从管理界面添加所有信息。使用外键一切正常,但我需要做一些 sql 查询,而不是一个。在他们描述的文档中,就像一个 sql 查询,但他们有choice_set.all()
. 它怎么可能与我的模型有关?我需要模板(html)中的所有信息,你能给我一些例子,它是如何工作的吗?谢谢。