Yuval Adam
Yuval Adam

Reputation: 165232

Selecting a related set of objects in Django

I have two models:

class ModelA(models.Model):
    name = models.CharField()

class ModelB(models.Model):
    a = models.ForeignKey(ModelA)
    value = models.CharField()

ModelB always belongs to a ModelA. I have a certain query that filters my ModelBs:

ModelB.objects.filter(value='foo')

From that QuerySet I need to retrieve the matching ModelA set. So I tried this:

>>> ModelB.objects.filter(value='foo').values('a')
[{'a': 2}, {'a': 4}, {'a': 6}]

But as you can see that only got me the object ids. How can I fetch the objects themselves?

Upvotes: 0

Views: 778

Answers (2)

Yuval Adam
Yuval Adam

Reputation: 165232

Currently I have this little number:

model_a_list = ModelB.objects.filter(value='foo').values('a')
ModelA.objects.filter(id__in=model_a_list)

Any better ways to do this would be much appreciated.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599590

If you want ModelAs, you have to ask for ModelAs.

ModelA.objects.filter(modelb__value='foo')

Upvotes: 4

Related Questions