Reputation: 923
I have the following models.
class Model1(models.Model):
name = models.CharField()
class Model2(models.Model):
name = models.CharField()
model1 = models.ForeignKey(model1)
class Model3(models.Model):
name = models.CharField()
model2 = models.ForeignKey(model2)
flag = models.BooleanField(blank=False)
so my display should be like, Model2.name
and Model1.name
on the listing page.
conditions are: I should only display Model2
instances which at least have one Model3.flag = True
So right now I am getting all the Model2
objects in the list and iterate over Model3
.
I am not able to properly use select_related()
for the model.
Can any one help.
thanks.
Upvotes: 0
Views: 77
Reputation: 23871
Something like:
qs = Model2.objects.filter(model3__flag=True).select_related('model1').distinct()
for m2 in qs:
print m2.model1.name, m2.name
# only fetch the names,
# this works if you treat duplicated ('name', 'model1__name') tuples same and show them once.
qs = qs.values('model1__name', 'name')
for x in qs:
print x['model1__name'], x['name']
Upvotes: 1