0

我在Django應用程序中有以下模型: 如何獲取此模型中任何選定content_object的「name」屬性並將其顯示在modelAdmin類的list_display中只顯示GenericForeign Key對象的鍵。請真的需要幫助。獲取GenericForeign鍵對象的名稱屬性

class Checkout(models.Model): 
    checkout_date = models.DateTimeField(auto_now_add=True) 
    updated = models.DateTimeField(auto_now=True) 
    check_in_complete = models.BooleanField(default=False, editable=False) 
    content_type = models.ForeignKey(ContentType, 
            limit_choices_to={"model__in": ('Facilitator', 'Enumerator', 'Tutor')}) 
    object_id = models.PositiveIntegerField(verbose_name='Receiver') 
    content_object = GenericForeignKey('content_type', 'object_id') 
+0

你試過'my_checkout.content_object.name'嗎? – Selcuk

回答

0

由於GenericForeignKey是不正常的領域對象,你不能在過濾器中使用它:

Checkout.objects.filter(content_object=other_obj) # this will fail 

但是,如果你要訪問的對象的name財產結帳時使用GenericForeignKey相關你可以這樣做:

name = checkout_obj.content_object.name 
+0

obj.content_object工作正常。請在你的最後確認。 Checkout.objects.filter(content_object = other_obj)會失敗,正如你所說的 – rohanagarwal

+0

謝謝,你是對的!我更新了我的答案。我很困惑它不適用於過濾器。它直接在一個對象上工作。 – AKS