Wednesday, 8 May 2019

How to do an exclude django query on multiple foreign key

My model example:

class Thing(models.Model):

    alpha = models.ForeignKey('auth.User', on_delete=models.CASCADE,
                             related_name='alpha_thing')

    beta = models.ForeignKey('auth.User', on_delete=models.CASCADE,
                               related_name='beta_thing')
    assigned_at = models.DateTimeField(
        _('assigned at'),
        null=True,
        help_text=_('Assigned at this date'))

I wish to query all the users which don't have a Thing with an assigned_at date, ie they could have other Things, but that should have a date set.

I've tried:

return User.objects.exclude(
    alpha_thing__assigned_at__isnull=True
).exclude(
    beta_thing__assigned_at__isnull=True
).all()

but the result is empty (the thing table is empty, so i'm not sure if it has something to do with the join?).



from How to do an exclude django query on multiple foreign key

No comments:

Post a Comment