ContentType.objects.get_for_model(obj) 在代理模型对象上使用时返回基础 class 模型

ContentType.objects.get_for_model(obj) returning base class model when used on a proxy model object

我有一个从另一个模型派生的代理模型。现在我创建这个代理模型的对象,并尝试使用 ContentType.objects.get_for_model(obj) 它 returns 基本 class 内容类型对象找出内容类型对象,而不是给我代理模型内容类型。我正在使用 Django 1.7.8。

class BaseModel(models.Model):
    field1 = models.CharField(max_length=200)
    field1 = models.CharField(max_length=200)


class ProxyModel(BaseModel):
    class Meta:
        proxy = True

现在我得到一个代理模型的对象

proxy_obj = ProxyModel.objects.get(field1=1)

并尝试查找 proxy_obj

的内容类型 class
content_type = ContentType.objects.get_for_model(proxy_obj)

但这让我得到了 BaseModel 的内容类型对象,而不是 ProxyModel。为什么这是一种荒谬的行为?还是我做错了什么?

来自 django-docs 的 get_for_model 方法:

Takes either a model class or an instance of a model, and returns the ContentType instance representing that model. for_concrete_model=False allows fetching the ContentType of a proxy model.

你必须通过 for_concrete_model=Falseget_for_model(),像这样:

content_type = ContentType.objects.get_for_model(proxy_obj, for_concrete_model=False)

为了获取代理模型的ContentType,您需要将参数for_concrete_model=False传入get_for_model().

示例:

content_type = ContentType.objects.get_for_model(proxy_obj,
                                                 for_concrete_model=False)

有关详细信息,请参阅 official docs

proxy_obj._meta.verbose_name.title() I think is better