Filter 2 models with ContentType in Django

2019-05-17 16:42发布

问题:

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!

回答1:

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