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?
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)
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')
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With