Pablo Guerrero
Pablo Guerrero

Reputation: 1064

django: How to get objects from a ContentType instance

I want to get a queryset of objects from a ContentType instance and then be able to filter them. From the doc, it is possible to get() an object using:

ct.get_object_for_this_type(**kwargs)

How can I make a similar filter() for that instance?

Upvotes: 6

Views: 2446

Answers (2)

Resley Rodrigues
Resley Rodrigues

Reputation: 2288

Since you have the ContentType instance you can do ct.model_class() to get the model class and then use it as you normally would.

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

Upvotes: 13

binpy
binpy

Reputation: 4194

As ContentType model has three fields app_label, model and name. So you can easily filter through these fields.

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

Example model:

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

    ....

Upvotes: 1

Related Questions