Reputation: 3466
I currently have a few models that either do or don't directly relate to a user. User
Region
and Location
.
User
is related to Location
through a ForeignKey manager
and Region
is related to Location
through a ForeignKey region
.
My question is what would be the correct queryset to show the relationship between the User
and the Region
for example if I were to return all the Regions that belonged to a certain user.
class Region(models.Model):
name = models.CharField(max_length=255)
...
class Location(models.Model):
region = models.ForeignKey(Region, blank=True, null=True)
manager = models.ForeignKey(User, blank=True, null=True)
...
I want to try and avoid having a direct relationship between User
and Region
if I can help it.
Upvotes: 2
Views: 39
Reputation: 99630
Assuming the user
variable is a User
instance,
You can have a lookup like this:
regions = Region.objects.filter(location__user=user)
Basically, for the reverse foreign key relationship in the queryset, you would use the lowercase modelname for the field lookup - location
in this case.
If such a relationship does not exist, regions.count()
would be 0
Documentation of this feature is here
Another way of achieving this is,
regions = user.location_set.values('region') #or values_list - or however you want this
Upvotes: 4