2016-10-20 13 views
0

私のようなモデルを持っている場合は、以下:モデル内のすべての外部キーを反復処理する方法は?

class Keyword(models.Model): 
    model1 = models.ForeignKey(Model1, null=True, blank=True, default=None) 
    model2 = models.ForeignKey(Model2, null=True, blank=True, default=None) 
    model3 = models.ForeignKey(Model3, null=True, blank=True, default=None) 
    model4 = models.ForeignKey(Model4, null=True, blank=True, default=None)  
    not_foreign_key = models.CharField(max_length=10, null=True, blank=True) 

は、どのように私は、各外部キーを反復処理することができますか?

私はこのようなループのためのいくつかの並べ替え(擬似コード)想像しています:

for each foreign key in Keyword: 
    do something with the foreign key 

はあなたの助けをいただき、ありがとうございます。

+1

の可能性のある重複した[ジャンゴ外部キー:?関連受けるモデルを](http://stackoverflow.com/questions/10347210/django -foreign-key-get-related-model) – ozgur

+0

フィールドの説明を反復するか、モデルインスタンスのすべての外部キーフィールドにアクセスしますか? – Sebastian

+0

@ozgurはい、それは基本的には、ありがとうございます。何かのようなもの:Keyword._meta.fieldsのフィールドの場合: field.get_internal_type()== "ForeignKey":... –

答えて

2

あなたは、すべての外部キー情報を取得するために、プライベートAPIを使用することができます。

# 'instance' is an instance of any kind of Django model 
fields = instance._meta._get_fields(forward=True, reverse=False) 
for field in fields: 
    obj_field_value = field.value_from_obj(instance) # This is the value the instance has for this field 
    foreign_key_related_model = field.related_model # returns the model the foreign key links to. There are plenty more properties here 
+0

ご協力いただきありがとうございます。私はあなたが書いたことを消化するのに時間を費やすでしょう。 –

+0

Djangoは、 '_get_fields()'の代わりにpublicメソッド 'get_fields()'を使うことをお勧めします。https://docs.djangoproject.com/en/1.10/ref/models/meta/#django.db.models .options.Options.get_fields – Risadinha

+0

@Risadinhaパブリック関数に対して 'forward'と 'reverse'のパラメータを指定することをお勧めします。プライベートAPIを使用せずに動作させることはできませんでした。 – Sebastian