[Answered ]-Get Records from Referenced Table "Minus" All The Records referenced from the Referencing Table

1๐Ÿ‘

โœ…

You can go with the following straightforward approach:

User.objects.exclude(pk__in=A.objects.values_list('current_user_id', flat=True))

A.objects.values_list('current_user_id', flat=True) returns a list of User model primary keys that are referenced by the A model. User.objects.exclude(pk__in=...) helps to get all other users.

In other words, this expression returns all users that are not related to A.

Also see:

๐Ÿ‘คalecxe

1๐Ÿ‘

Check out the Django docs on Many-to-one Relationships. In the โ€œQuerying in the opposite directionโ€ example, you can see that within the filter you can access the related object.

In your example, you can get all User records without a related A object with the query:

User.objects.filter(a__isnull=True)

In the case of one-to-many ForeignKeys, I typically specify the related_name argument as the plural version of the model name. It helps to make the one-to-many relationship clearer.

In your example it would look like this:

class User(models.Model)
    pass

class A(models.Model):
    current_user_id = ForeignKey(User, related_name='as')

# now the above query would look like this:
User.objects.filter(as__isnull=True)

It helps clarify which model is the one and which model is the many in the one-to-many relationship.

๐Ÿ‘คpcoronel

Leave a comment