【问题标题】:How to get the class name of a ContentType in django如何在 django 中获取 ContentType 的类名
【发布时间】:2013-11-28 16:30:00
【问题描述】:

如何获取 ContentType 字符串中的类名?我试过这种方法,但没有成功:

class StreamItem(models.Model):
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    pub_date = models.DateTimeField(default=datetime.now)

    content_object = generic.GenericForeignKey('content_type', 'object_id')
    content_class = content_type.__name__

    def __unicode__(self):
        return self.content_class

任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: python django django-models django-contenttypes


    【解决方案1】:

    更新:在澄清要求模型名称的问题后,通过属性model访问它,您可以通过这种方式在运行时访问它:

    <STREAMING_ITEM_INSTANCE>.content_type.model
    

    我测试过:

    from testso_app.models import StreamItem
    from django.contrib.auth.models import User
    from django.contrib.contenttypes.models import ContentType
    a = User.objects.all()[0]
    cctt = ContentType.objects.all()
    si = StreamItem(user=a, content_type=cctt[0], object_id=1)
    si.content_type.model
    

    并得到:u'author'

    【讨论】:

    • 感谢您的回答!我不能用它作为属性吗?
    • 我试过了。但它给我的名字是ContentType,而不是模型的实际名称。
    • 好的。但是你的意思是content_class = content_type.__class__.__name__ 还是你写的那个?
    • 你问的是类名,不是型号名,所以我会再次编辑答案
    • 是的,我不想更改content_type,我只想要content_type 的类名(content_class)。行。将等待..
    猜你喜欢
    • 2012-09-30
    • 2014-12-15
    • 2013-12-04
    • 2019-09-24
    • 2011-11-02
    • 2011-07-04
    • 2018-03-10
    • 2014-02-28
    • 2015-09-25
    相关资源
    最近更新 更多