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
- [Answered ]-Getting the amount of a plan using stripe API in django
- [Answered ]-Why not calling save() on one model, while calling on another
- [Answered ]-What is the concept behind "text" withiin Haystack SearchIndex
- [Answered ]-Python doesn't interpret UTF8 correctly
Source:stackexchange.com