2017-09-27 17 views
0

私はクラスAにForeignKeyリレーションを含むクラスBを持っています。私はBをインスタンス化するときにフィールド 'a'にアクセスできますが、リバースリレーション(自動的に作成する必要があります)私はその逆の患者とattribute_setフィールドにアクセスすることはできませんが、患者や属性セット引数で新しいAttributeSetInstanceを作成しようとするとDjangoの外部キー後方関係は機能しません

from django.db.models import Model, CharField, DateField, ForeignKey 
from django.urls import reverse 

class Patient(Model): 

    GENDER = (
     ('M', 'Male'), 
     ('F', 'Female'), 
     ('U', 'Unknown'), 
    ) 

    last_name = CharField(max_length=128, null=False) 
    first_name = CharField(max_length=128, null=False, default='') 
    gender = CharField(max_length=1, choices=GENDER, null=False) 
    dob = DateField(null=False) 

    def get_absolute_url(self): 
     return reverse('patient_detail', args=[str(self.id)]) 

    def __str__(self): 
     return '{}, {} ({}, {})'.format(self.last_name, self.first_name, self.gender, self.dob) 


class AttributeSet(Model): 

    name = CharField(max_length=128, null=False) 
    description = CharField(max_length=256, blank=True, default='') 

    def get_absolute_url(self): 
     return reverse('attribute_set_detail', args=[str(self.id)]) 

    def __str__(self): 
     return self.name 


class AttributeSetInstance(Model): 

    patient = ForeignKey('Patient', null=False) # Automatic 'attribute_set_instance_set' backward relation? 
    attribute_set = ForeignKey('AttributeSet', null=False) 

    def get_absolute_url(self): 
     return reverse('attribute_set_instance_detail', args=[str(self.id)]) 

    def __str__(self): 
     return self.attribute_set.name 

:具体的には、私は、次のクラス定義を持っています。同様に:

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 
>>> from app.models import Patient, AttributeSet, AttributeSetInstance 
>>> p = Patient(last_name='Doe', first_name='John', gender='M', dob='1973-07-16') 
>>> p 
<Patient: Doe, John (M, 1973-07-16)> 
>>> a = AttributeSet(name='Set1') 
>>> a 
<AttributeSet: Set1> 
>>> i = AttributeSetInstance(patient=p, attribute_set=a) 
>>> i 
<AttributeSetInstance: Set1> 
>>> i.patient 
<Patient: Doe, John (M, 1973-07-16)> 
>>> i.attribute_set 
<AttributeSet: Set1> 
>>> p.attribute_set_instance_set 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
AttributeError: 'Patient' object has no attribute 'attribute_set_instance_set' 
>>> 

したがって、i.patientは動作しますが、p.attribute_set_instance_setはそうではありません。私が理解できる限り、ForeignKey関係に割り当てられたデフォルトのマネージャーは、後方関係に「_set」接尾辞を追加します。

私が間違っていることを知っていますか?それは大きな助けになるでしょう。 それはあなたがどんな存在しないはずのアンダースコアを追加しました

ラルフ

答えて

1

...おそらく愚かなものです。デフォルトの関連する名前は、モデルの小文字の名前に_setであるため、AttributeSetInstanceの場合はattributesetinstance_setです。

アンダースコアバージョンを使用する場合は、ForeignKeyフィールドへの明示的なrelated_name引数として設定できます。

+0

ありがとうございます!それだった!マイグレーションの出力に基づいて推測できました(フィールドがアンダースコアなしで潰れて表示されます)。 – Ralph

関連する問題