[Answer]-Django Query Relations Behaviour

1👍

Your question is a little vague, but if I understand you correctly it would work like this:

class A(models.Model):
    pass

class B(models.Model):
    a = models.ForeignKey(A)
    some_field = models.IntegerField()

a.filter(b__some_field=5).distinct()

This JOINs the two tables and filters on b‘s some_field. Then distinct() makes sure that only unique as are returned. See the documentation on lookups that span relationships.

0👍

My solution was a lot more simpler than I initially thought. I didn’t know you could filter associated models so easily. Here’s what I ended up with:

class A(models.Model):
    pass

class B(models.Model):
    a = models.ForeignKey(A)
    location = models.ForeignKey(Location)

a.filter(b__location=request.user.profile.location)
👤Callum

Leave a comment