Reputation: 1165
Okay is there a way to filter the objects so that you only get records with associated records. Is it a right join maybe?
Basically, I only want to select records from A that B has a foreign key for whilst using a WHERE clause on B. Am i making it sound more complicated than it is? I don't need the records from B, just the A; maybe a subquery?
I'm relatively new to Django's queries and i've only just done some of the simpler stuff.
Upvotes: 0
Views: 49
Reputation: 1165
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)
Upvotes: 0
Reputation: 48982
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 a
s are returned. See the documentation on lookups that span relationships.
Upvotes: 1