django:如何从 ContentType 实例获取对象

django: How to get objects from a ContentType instance

我想从 ContentType 实例中获取对象的查询集,然后能够过滤它们。从文档中,可以使用 get() 一个对象:

ct.get_object_for_this_type(**kwargs)

如何为该实例制作类似的 filter()

因为 ContentType model 有三个字段 app_labelmodelname。因此您可以轻松筛选这些字段。

notifications = Notification.objects.filter(content_type__model='Comment', object_id=1)

示例模型:

class Notification(models.Model):
    content_type = models.ForeignKey(ContentType, related_name='notifications', on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField(_('Object id'))
    content_object = GenericForeignKey('content_type', 'object_id')

    ....

由于您拥有 ContentType 实例,因此您可以 ct.model_class() 获取模型 class 然后像往常一样使用它。

model_class = ct.model_class()
model_class.objects.filter(**kwargs)