Yuval Adam
Yuval Adam

Reputation: 165182

Referencing related field values in Django

Consider a simple ForeignKey relationship:

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

class ModelB(models.Model):
    my_field = CharField()
    parent = ForeignKey(ModelA)

So I can do this:

my_fields = ModelB.objects.all().values('my_field')

Is there any way to reference other_field in the same call? I would assume something like this is possible:

all_fields = ModelB.objects.all().values('my_field', 'parent.other_field')

But apparently that's not the case. What's the easiest way to fetch the related field values?

If this means that the Django ORM needs to prefetch the related values resulting in a heavy query, so be it. I'm looking for the most elegant way to do this.

Upvotes: 2

Views: 348

Answers (1)

second
second

Reputation: 28637

as per the docs you can use

...values('parent__other_field')

Upvotes: 5

Related Questions