I'm sending api like:
[
{
"id": 1,
"name": "Burger",
"name_ru": "Burger",
"name_en": "Burger",
"img": null,
"parent_category": 1
},
{
"id": 3,
"name": "Pizza",
"name_ru": "Pizza",
"name_en": "Pizza",
"img": null,
"parent_category": 1
}
]
how can edit this api? I want to send parent_category with id
and name
, not just id
.
My views.py
:
class TestList(APIView):
def get(self, request, pk, format=None):
cc = Child_Category.objects.filter(parent_category_id = pk)
serializer = ChildCategorySerializer(cc, many=True)
return Response(serializer.data)
My models.py
:
class Parent_Category(models.Model):
name = models.CharField(max_length=255)
name_ru = models.CharField(max_length=255)
name_en = models.CharField(max_length=255)
img = models.ImageField(blank=True, null=True)
def __str__(self):
return self.name_en
class Meta:
verbose_name_plural = 'Parent Categories'
class Child_Category(models.Model):
name = models.CharField(max_length=255)
name_ru = models.CharField(max_length=255)
name_en = models.CharField(max_length=255)
parent_category = models.ForeignKey(Parent_Category, on_delete=models.CASCADE)
img = models.ImageField(blank=True, null=True)
def __str__(self):
return self.name_en
class Meta:
verbose_name_plural = 'Child Categories'
CodePudding user response:
you have to use two serializers
class TestList(APIView):
def get(self, request, pk, format=None):
parent_category = ParentCategory.objects.get(id=pk)
child_categories = Child_Category.objects.filter(parent_category_id = pk)
parent_serializer = ParentCategorySerializer(parent_category)
child_serializer = ChildCategorySerializer(child_categories, many=True)
data = {
"parent_category": parent_serializer.data,
"child_categories": child_serializer.data
}
return Response(data)
if you want to add the parent_category,child_categories in one data
[
{
"id": 1,
"name": "Burger",
"name_ru": "Burger",
"name_en": "Burger",
"img": null,
"parent_category": 1,
"parent_name":xyz
},
{
"id": 3,
"name": "Pizza",
"name_ru": "Pizza",
"name_en": "Pizza",
"img": null,
"parent_category": 1,
"parent_name":xyz
}
]
so you can do like this
class TestList(APIView):
def get(self, request, pk, format=None):
parent_category = ParentCategory.objects.get(id=pk)
parent_name = parent_category.name
child_categories = Child_Category.objects.filter(parent_category_id = pk)
result_data=[]
for data in child_categories:
dict_data = {
"id": data.id,
"name": data.name,
"name_ru": data.name_ru,
"name_en": data.name_en,
"img": data.img,
"parent_category" : data.parent_category,
"parent_name":parent_name
}
result_data.append(dict_data)
return Response(result_data)
And if you want to use serializer then you need to create a new serilizer with the of both child and parent.