【问题标题】:Get the name attribute of a GenericForeign key object获取 GenericForeign 键对象的名称属性
【发布时间】:2016-04-27 22:31:03
【问题描述】:

我在 Django 应用程序中有以下模型: 如何获取此模型中任何选定 content_object 的“名称”属性并将其显示在 modelAdmin 类的 list_display 中,而不是仅显示 GenericForeign Key 对象的键。我真的需要帮助。

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')

【问题讨论】:

  • 你试过my_checkout.content_object.name吗?

标签: django django-models django-contenttypes generic-foreign-key


【解决方案1】:

由于GenericForeignKey不是普通的字段对象,所以不能在过滤器中使用:

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

但是,如果您想使用 GenericForeignKey 访问与您的结帐相关联的对象的 name 属性,您可以执行以下操作:

name = checkout_obj.content_object.name

【讨论】:

  • obj.content_object 工作正常。请您确认。 Checkout.objects.filter(content_object=other_obj) 如你所说会失败
  • 谢谢,你是对的!我更新了我的答案。我对它在过滤器中不起作用感到困惑。它确实直接作用于对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 2022-08-23
  • 1970-01-01
  • 2021-09-03
  • 2019-05-23
  • 2019-07-11
相关资源
最近更新 更多