1. ホーム
  2. ジャンゴ

djangoにおけるrelated_nameの役割

2022-03-02 12:29:36

簡単なことから始めましょう。果物の屋台に行って、人参の実と桃の2種類の果物を買いました。その後、果物の屋台の主人は、100歳のおじいさんに関係すると思われる大切な宝物をなくしたと深く感じ、集金の請求書に目を通し、食べ物屋の請求書を見て、この人は私の宝物を買ってくれた、私はこの人から買った宝物を見ようと思いました!と胸を締め付けました。店主は、食べる紳士の名前を通して買った果物を見つけると、百万年前の桃だけでなく、十億年前の高麗人参もあることが分かった、吠えた!!!!

食べる紳士はどんな運勢だったんだろう?

ここでは、上記のミニプロットをもとに、買い手モデルと果物モデルの2つのモデルを定義し、1人の買い手が複数の果物モデルに対応する、単純な1対多モデルとする。

class Buyer(models.Model).
    name = models.CharField(verbose_name='buyer_name', max_length=10) 
    Alipay_id = models.CharField(verbose_name='paypal account') 
    age = models.IntegerField(verbose_name='Buyer's age', blank = True)


class Fruit(models.Model): 
    Buyer = models.ForeignKey(Buyer, related_name='buyer_fruit') 
    fruit_name = models.CharField(verbose_name='fruit_name', max_length=10) 
    weight = models.FloatField(verbose_name='fruit_weight') 

通常、購入者がどの果物を買ったかを調べるには、まず条件から購入者の情報を探し、次に購入者の情報から購入した果物を探しますが、この場合は次のようになります。

# First get the object in the table pointed to by the foreign key in the fruit model.

buyer = Buyer.objects.filter(age = 100).first()

# Then get the data in the child table via the '_set' method.

fruits = buyer.fruit_set.all() 

"""
django defaults to a foreign key property for each primary table object, which can be used to look up information about all the child tables that belong to the primary table. The name of this attribute is by default the name of the child table in lowercase plus _set() to represent, here our main table is buyer, word table is fruit, so the main table foreign key attribute is fruit_set
"""

上記の fruit_set は、django がオブジェクトバイヤーのためにデフォルトで作成する外部キーのプロパティです。個人的には、メインテーブルの外部キーをカスタムで定義すると、より使い慣れたものになるのでおすすめです そして、この機能を実現するためのrelated_nameですが、ワードテーブルで外部キーを定義する際に、以下のようにメインテーブルのこのワードテーブルに対応する外部キー属性を指定するrelated_nameフィールドを追加してください。

class Fruit(models.Model): 
    ForeignKey(Buyer, related_name='buyer_fruit') 
"""
Main table:buyer
sub-table:fruit
The corresponding foreign key attribute of the child table in the main table: related_name='buyer_fruit'
"""

そして、カスタム外部キーによって、必要な情報を見つけることができます。

# First get the object in the table pointed to by the foreign key in the fruit model.

buyer = Buyer.objects.filter(age = 100).first()

# Then get all the information in the child table by the custom foreign key in the child table.

fruits = buyer.buyer_fruit.all()