Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 586
Pablo Guerrero Avatar asked Jan 04 '23 03:01

Pablo Guerrero


2 Answers

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)
like image 56
Resley Rodrigues Avatar answered Jan 16 '23 21:01

Resley Rodrigues


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

    ....
like image 40
binpy Avatar answered Jan 16 '23 21:01

binpy