代码之家  ›  专栏  ›  技术社区  ›  damd

在Django admin中显示只读GenericForeignKey值

  •  0
  • damd  · 技术社区  · 6 年前

    User 或者 Organization

    class Project(models.Model):
        # ...
        client_type = models.ForeignKey(
            'contenttypes.ContentType',
            on_delete=models.SET_NULL,
            blank=True,
            null=True,
            limit_choices_to=(
                models.Q(app_label='users', model='user') |
                models.Q(app_label='organizations', model='organization')
            )
        )
        client_id = models.PositiveIntegerField(blank=True, null=True)
        client = GenericForeignKey('client_type', 'client_id')
        # ...
    

    @admin.register(models.Project)
    class ProjectAdmin(admin.ModelAdmin):
        list_display = (
            '__str__',
            'client',
        )
    

    但是,我找不到一个简单的方法来在项目的实际更改页面中显示客户机的名称。我尝试了显而易见的方法:

    fields = (
        'name',
        'client',
    )
    

    client 字段名无效。我读了 Using generic relations as an inline Django文档的一部分,但他们的例子似乎…倒退了?

    我只想显示客户的名字,不需要编辑。有什么建议吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   dirkgroten    6 年前

    这个 list_display GenericForeignKey 字段,则需要显式将其设为只读:

    read_only_fields = ('client', )