如何在django中获取ContentType的类名

时间:2013-11-28 16:30:00

标签: python django django-models django-contenttypes

如何在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

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

1 个答案:

答案 0 :(得分:2)

更新:在询问模型名称的问题后,通过属性model访问它的方式,您可以通过以下方式在运行时访问它: / p>

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

相关问题