[Answered ]-Django ORM Foreign Key Values how to return as single dictionary

1๐Ÿ‘

โœ…

you can do so using annotation and F, this is a sample code :

from django.db.models import F
items = MasterModel.objects.select_related('town').annotate(child_location=F('town__location'))

for item in items:
    print(f"MasterModel: {item.town_id}, Child Location: {item.child_location}")

where F helps you reach the value of the child class field.

another way which uses django-rest-framework would be to use serializers which do such thing automatically,

this would be your serializers.py file:

class ChildModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChildModel
        fields = '__all__'

class MasterModelSerializer(serializers.ModelSerializer):
    town_location = serializers.CharField(source='town.location', read_only=True)

    class Meta:
        model = MasterModel
        fields = ['id', 'town', 'town_location']

and you this code would display the data:

data = MasterModel.objects.all()
serializer = MasterModelSerializer(data, many=True)
print(serializer.data[0])
๐Ÿ‘คtareq albeesh

0๐Ÿ‘

Simply do this:

items = MasterModel.objects.values('town_id', 'town__location')

You can also use alias

๐Ÿ‘คAhtisham

Leave a comment