Samuel Colvin
Samuel Colvin

Reputation: 13279

Elegant way of finding related fields in Django

So I have an instance of Django model ("item") and a list of fields and related fields i want to find. Currently I'm doing this:

related_fields = ['customer__name', 'customer__address__postcode', 'date']
for related_field in related_fields:
    sub_item = item
    for part in related_field.split('__'):
        sub_item = getattr(sub_item, part)
    item_fields.append(sub_item)

I hope that makes sense, but is this the most efficient way of doing it? Surely there must be a Django utility function somewhere that does this in SQL much more quickly?

Upvotes: 1

Views: 46

Answers (1)

falsetru
falsetru

Reputation: 369114

You can use QuerySet.values_list. For example:

related_fields = ['customer__name', 'customer__address__postcode', 'date']
item_fields = Item.objects.filter(pk=item).values_list(*related_fields, flat=True)[0]

Upvotes: 1

Related Questions