ForeignKey关系的“另一面”

时间:2013-02-24 14:07:37

标签: django

我多次阅读thisthis教程,但我不明白,如何执行以下操作:

模型:

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查询中获取有关汽车的所有信息。它是如何用docs写的:

car = get_object_or_404(Car, pk=car_id)

但是here是一个奇怪的(它描述了一个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-querys,而不是一个。在文档中,他们描述了它,就像一个sql查询,但他们有choice_set.all()。它如何与我的模型有关?我需要模板中的所有信息(html),你能给我一些例子,它是如何工作的? 感谢。

2 个答案:

答案 0 :(得分:2)

相关管理员的名称是从模型名称自动生成的。您有car.carpictures_setcar.caroptions(这不是“设置”,因为它是一对一的关系。)

您可以定义自己的相关名称:

class Car(models.Model):
    ...

class CarOptions(models.Model):
    car = models.OneToOneField(Car, primary_key=True, related_name='options')

class CarPictures(models.Model):
    car = models.ForeignKey(Car, related_name='pictures')

然后您将拥有car.optionscar.pictures

Related objects reference

答案 1 :(得分:0)

让我们说这是你的观点

 cars = Car.objects.filter()
 car_options = CarOptions.objects.filter()
 car_pictures = CarPictures.objects.filter()

这里是如何与html相关的

{% for car in cars %}
    {% for option in car.car_options %}

    {% endfor %}

    {% for picture in car.car_pictures %}

    {% endfor %}
{% endfor %}