Get Records from Referenced Table "Minus" All The Records referenced from the Referencing Table

StackOverflow https://stackoverflow.com/questions/23530797

  •  17-07-2023
  •  | 
  •  

Question

I have a model A that has a foreign Key to the User Model (current_user_id).

User.objects.filter() gives me all users.

How can i add an additional exclude to find all the User objects that are not currently referenced in A?

For Example

Users
=====
1
2
3

A
===
id current_user_id
1      1
2
3

I want to get only Users with id 2 and 3 (And not 1 because it is referenced in A)

Was it helpful?

Solution

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:

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top