Reputation: 369
In Django, if I have a model such as a Building which is OneToOne related to a (Django Auth) Group containing users, how can I find all the buildings to User belongs to (maybe those are all the buildings the User works in)? Building is one to one with Group so building has a group foreign key field called 'group'.
I've tried
Building.objects.filter(group__contains=user)
Building.objects.filter(group_user_set__contains=user)
I'm getting no matches when there should be matches.
Upvotes: 5
Views: 7860
Reputation: 3125
If it's a one to one relationship why not just return the groups?
result = []
u = User.objects.get(your user here)
for group in u.groups.all():
result.append(group.whateverYourForeignKeyFieldIsCalled)
return result
Upvotes: 0
Reputation: 1586
Using contains
is not the right choice since it searches for expression inside field (string) not within the set. Try using:
Buildings.objects.filter(group__user=user)
Upvotes: 7