Return A Nested List Of One Model
I have a lookups table that contains course categories and subcategories separate: { 'id': 138, 'lookup': 'CRS_CTGRY', 'attr1': 'Arts and Humanities',
Solution 1:
You need to implement serializer for your subcategory:
classSubcategorySerializer(serializers.ModelSerializer):
classMeta:
model = Lookupsfields= ( 'id', 'lookup', 'attr1', 'attr2', 'attr3',)
And use it in your Category Serializer when you select all related subcategories:
classCategorySerialier(serializers.ModelSerializer):
subcategories = serializers.SerializerMethodField(read_only=True)
classMeta:
model = Lookups
fields = ( 'id', 'lookup', 'subcagories')
defget_subcategories(self, obj):
subs = Lookups.objects.filter(attr3=obj.id)
return SubcategorySerializer(subs,many=True).data
Solution 2:
If these are two models, and one serialize inside the other. http://www.django-rest-framework.org/api-guide/relations/#nested-relationships
Post a Comment for "Return A Nested List Of One Model"