【问题标题】:Django GenericForeignKey in the admin管理员中的 Django GenericForeignKey
【发布时间】:2023-03-24 11:40:02
【问题描述】:
class Comment(models.Model):
    text = models.TextField()
    timestamp = models.DateTimeField(auto_now_add = True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

class Product(models.Model):
    name = models.CharField(max_length = 40)
    comments = generic.GenericRelation(Comment)

    def __unicode__(self):
        return self.name

如果可能,我会在 Django 管理员中,在“评论”页面下,查看内容对象的 __unicode__,例如可以是产品。

这样的:

所有 cmets

评论 1 - 对产品 - Foo Bar(产品的unicode) - 时间戳

评论 2 - 到 UserProfile - Foo Bar (unicode of UserProfile) - 时间戳

等等

admin.py 的想法?

【问题讨论】:

    标签: python django django-admin


    【解决方案1】:

    我建议在 Comment 模型中添加 unicode 方法:

    def __unicode__(self):
        return 'Comment %s - to  a %s - %s' % (self.pk, self.content_type, self.content_object.__unicode__(), self.timestamp)
    

    如果您使用的是标准 ModelAdmin,则无需更改 admin.py。

    【讨论】:

    • 感谢您的回复。如何在模型管理页面的字段中显示方法__unicode__
    • 你的意思是当使用list_display的时候?:list_display('__unicode__',)
    • 你摇滚!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 2014-08-10
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多