create nested JSON from DB output in django rest framework -
i trying create nested json db output, using django rest framework. have created models, serializers , views.py follows:
models.py
class secondmodel(models.model): userno = models.charfield(max_length=30, primary_key=true) username = models.charfield(max_length=250) period = models.charfield(max_length=250) class meta: managed = false db_table = 'view1' class firstmodel(models.model): code = models.foreignkey(secondmodel,db_column='code', related_name='clients', primary_key=true) name = models.charfield(max_length=250) study = models.charfield(max_length=250) class meta: managed = false db_table = 'view2'
views.py:
class nestedviewset(viewsets.modelviewset): serializer_class = secondserializer queryset = secondmodel.objects.filter(userno=11) serializer = secondserializer(instance=queryset)
serializers.py:
class firstserializer(serializers.modelserializer): class meta: model = firstmodel fields = ('name', 'code', 'study') class secondserializer(serializers.modelserializer): clients = firstserializer(many=true,read_only=true) class meta: model = secondmodel fields = ('userno', 'username','period','clients')
the output getting below. getting "clients" empty list.
{ "userno": "11", "username": "smith,john", "period": "apr-17", "clients": []
}, {
"userno": "11", "username": "smith, john", "period": "apr-17", "clients": [] }
the output looking is:
{ "userno": "11", "username": "smith,john", "period": "apr-17", "clients": [ { "name" : "comp1", "code" : "abc111", "study" : "stu11" }, { "name" : "comp2", "code" : "abc222", "study" : "stu22" } ]
}
am missing here desired output?
Comments
Post a Comment