django: How to get objects from a ContentType instance
Asked Answered
Z

2

6

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?

Zeitler answered 25/11, 2017 at 13:19 Comment(0)
N
13

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)
Nil answered 25/11, 2017 at 17:12 Comment(0)
A
1

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

    ....
Acinaciform answered 25/11, 2017 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.