【问题标题】:How can I customize the display of a model using contenttypes in the admin?如何在管理员中使用 contenttypes 自定义模型的显示?
【发布时间】:2011-09-14 04:49:49
【问题描述】:

我有这些模型:

class App(models.Model):
  name = models.CharField(max_length=100)

class ProjectA(models.Model):
  name = models.CharField(max_length=100)
  app  = models.ForeignKey(App)

class ProjectB(ProjectA):
  pass

class Attachment(models.Model):
  content_type    = models.ForeignKey(ContentType)
  object_id       = models.PositiveIntegerField()
  project         = generic.GenericForeignKey("content_type","object_id")
  file            = models.FileField(upload_to=".")

我正在为管理员注册所有模型,并且正在取消注册组、用户和站点。问题是,当我在管理员中访问附件时,我看到它呈现如下:

在内容类型选择中,我看到了这个列表:

Attachment 有 GenericForeignKey 的原因是因为 ProjectA 和 ProjectB 都需要访问它。我知道 ProjectA 和 ProjectB 是相同的,但要求它们存储在 2 个单独的表中。我怎样才能让管理员可以使用附件类?我知道如何使用普通视图中的内容类型,但管理员不知道。

在附件类中,我只想选择项目 A 或项目 B,然后是所有项目 A 或所有项目 B 的列表,然后是我要附加的文件。

管理员可以这样做吗?我需要向用户显示对象 ID 列吗?

【问题讨论】:

    标签: django django-models django-admin django-contenttypes


    【解决方案1】:

    如果我没记错的话,你想要这个。 http://code.google.com/p/django-genericadmin/

    我的建议会有所不同。您将在 ProjectA、ProjectB 中添加更多表单作为内联。在你的 admin.py 中

    from django.contrib import admin
    from django.contrib.contenttypes import generic
    
    from myproject.myapp.models import Attachment, ProjectA, ProjectB
    
    class Attachmentline(generic.GenericTabularInline): #or generic.GenericStackedInline, this has different visual layout.
        model = Attachment
    
    class ProjectAdmin(admin.ModelAdmin):
        inlines = [
            Attachmentline,
        ]
    
    admin.site.register(ProjectA, ProjectAdmin)
    admin.site.register(ProjectB, ProjectAdmin)
    

    转到您的 ProjectA 或 ProjectB 管理员并查看新管理员。

    这不是您想要的,但它可以帮助您。否则你需要检查第一个链接。

    【讨论】:

    • 美丽的选择。谢谢!
    • 不知道有generic.GenericTabularInline
    【解决方案2】:

    你应该注意到

    " 知道 ProjectA 和 ProjectB 是 相同,但这是一个要求 它们存储在 2 个单独的表中”

    是不正确的。所有数据都存储在您的 app_projecta 表中,并且(仅)一些指针保存在表 app_projectb 中。如果您已经走上了这条路,我建议您从这条路开始:

    class App(models.Model):
      name = models.CharField(max_length=100)
    
    class Project(models.Model):
        name = models.CharField(max_length=100)
        app = models.ForeignKey(App)
    
    class ProjectA(Project):
      pass
    
    class ProjectB(Project):
      pass
    
    class Attachment(models.Model):
      project = models.ForeignKey(Project)
      file = models.FileField(upload_to=".")  
    

    这已经让你离你想去的地方更近了一点......

    【讨论】:

    • 谢谢。 GenericForeignKey 的选择字段呢?你会碰巧知道解决方案吗?
    • Udi 提出的方法不需要使用通用外键。您只能使用普通的旧外键引用 Project 模型。但是,一个缺点是项目可以既是项目A 又是项目B,或者两者都不是。如果您提供将 ProjectA 转换为 ProjectB 的可能性,则必须不时检查数据库的一致性。
    猜你喜欢
    • 2018-09-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2019-09-26
    • 2013-06-01
    • 1970-01-01
    相关资源
    最近更新 更多