Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter 2 models with ContentType in Django

I have 2 profile Models. And I am creating an "Attendee" object. How do I filter just between the 2 profiles?

class Profile1(models.Model):
    user = models.ForeignKey(User, null=True, unique=True)

class Profile2(models.Model):
    user = models.ForeignKey(User, null=True, unique=True)

class Attendee(models.Model):
    event = models.ForeignKey(Event)
    # This filters through everything... How do I filter down just to the 2 profile objects?
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    profile = generic.GenericForeignKey('content_type', 'object_id')

Thanks for your help!

like image 909
Modelesq Avatar asked Dec 16 '22 23:12

Modelesq


2 Answers

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

attendees = Attendee.objects.filter(content_type__model = 'Profile1')
like image 118
Ahsan Avatar answered Jan 10 '23 05:01

Ahsan


I'd go for

from django.contrib.contenttypes.models import ContentType
...

Attendee.objects.filter(
   content_type=ContentType.objects.get_for_model(Profile1))

to avoid comparing strings and bugs after refactoring classnames.

like image 29
Boern Avatar answered Jan 10 '23 05:01

Boern