2011-12-20 21 views
5

私は与えられたオブジェクトの_meta.fieldsを反復処理する汎用関数を持っています。 ManyToManyフィールドを除いて、すべてのフィールド名と値が正しくフェッチされます。 ManyToManyフィールドは完全に無視されているようです。私たちはm2mのフィールドからfksをどのように取得するのですか?多くのフィールドは_meta.fieldsには表示されません

def myfunc(self) 
    for field in self._meta.fields: 
     type = field.get_internal_type() 
     name = field.name 
     val = getattr(self,field.name) 

答えて

15

あなたはモデル内のすべてのフィールド名を取得したい場合は彼らはself._meta.many_to_many

0

です。 self._meta.many_to_many + self._meta.fieldsを使用する必要はありません。

[field.name for field in model._meta.get_fields()]を使用できます。

get_fieldsは(多対多の外部キーを含む)すべてのフィールド

Djangoのget_fieldsを返すことに注意してください:

def get_fields(self, include_parents=True, include_hidden=False): 
    """ 
    Returns a list of fields associated to the model. By default, includes 
    forward and reverse fields, fields derived from inheritance, but not 
    hidden fields. The returned fields can be changed using the parameters: 

    - include_parents: include fields derived from inheritance 
    - include_hidden: include fields that have a related_name that 
         starts with a "+" 
    """ 
関連する問題