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:
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.
- [Answered ]-Django: Customizing ManyToManyField form options
- [Answered ]-Django- CSRF and POSTing an Html form
- [Answered ]-Dealing with dependent objects in Django templates
- [Answered ]-Checkbox not working in a Django form (bug?)
- [Answered ]-Extending two related queries on same model in Django