0

これこのチュートリアルを何度も読みましたが、次のことを行う方法がわかりません。

モデル:

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

したがって、車に関するすべての情報を 1 つの 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()。管理インターフェイスからすべての情報を追加します。外部キーを使用すると、すべてうまく機能しますが、1 つではなく、いくつかの sql-query を実行する必要があります。ドキュメントでは、1つのSQLクエリのように説明されていますが、choice_set.all(). 私のモデルでどのように行うことができますか? テンプレート (html) 内のすべての情報が必要です。例を挙げていただけますか? ありがとう。

4

2 に答える 2

2

関連する管理者の名前は、モデル名から自動的に生成されます。andがcar.carpictures_setありますcar.caroptions(1 対 1 の関係であるため、これは「セット」ではありません)。

独自の関連名を定義できます。

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.optionsありcar.picturesます。

関連オブジェクトのリファレンス

于 2013-02-24T14:12:20.997 に答える
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 %}
于 2013-02-24T15:03:16.273 に答える