2014-05-18 98 views
2

解決對象我試圖穿越在一個通用的way-如何從Django的ForeignKey的領域

Django的對象,我不能得到相關對象:

# field_names has the names of some fields of object 

for field_name in field_names: 
    field = object._meta.get_field_by_name(field_name) 

    if isinstance(field[0], ForeignKey): 
     related = getattr(object, field[0].get_attname()) 

相關然後持有主鍵值。

但我如何訪問該對象?我錯過了什麼?

回答

1

實測值的溶液:

field = object._meta.get_field_by_name(field_name) 
if isinstance(field[0], ForeignKey): 
    fkey = {} 
    fkey['name'] = field[0].rel.get_related_field().name 
    fkey['value'] = getattr(object, field[0].get_attname()) 

    related = field[0].rel.to._default_manager.get(**{fkey['name']: fkey['value']}) 
2

你可以從rel底層對象相關:

field[0].rel.to 

可以通過使用get_field()簡化代碼位:

for field_name in field_names: 
    field = object._meta.get_field(field_name) 

    if isinstance(field, ForeignKey): 
     related = field.rel.to 
+1

然後相關的是模型類,而不是相關對象 –