我想根据膳食类别展示膳食。我正在使用Rest API的django rest框架。我可以展示肉类,但不是基于类别。模特是餐厅,膳食和膳食类。
这是我的模特
class Restaurant(models.Model):
name = models.CharField(max_length=150, help_text="name of restaurant")
slug = models.SlugField(max_length=150)
class Meal(models.Model):
restaurant = models.ForeignKey(Restaurant)
meal_category = models.ForeignKey('MealCategory')
name = models.CharField(max_length=120, help_text="name of the meal")
def __str__(self):
return self.name
class MealCategory(models.Model):
name = models.CharField(max_length=80, help_text="name of the category of meal")
slug = models.SlugField(max_length=80)
Serializers.py
class MealCategorySerializer(ModelSerializer):
# meal = SerializerMethodField()
class Meta:
model = MealCategory
class MealSerializer(ModelSerializer):
meal_category = MealCategorySerializer(read_only=True)
class Meta:
model = Meal
def get_meal(self, obj):
print('object of meal',obj)
instance = MealCategory.objects.get(slug=str(obj.slug))
meal_qs = instance.meal_set.filter(available=True)
meal = MealSerializer(meal_qs, many=True).data
return meal
class RestaurantSerializer(ModelSerializer):
owner = SerializerMethodField()
meal = SerializerMethodField()
class Meta:
model = Restaurant
read_only = ('id',)
def get_owner(self, obj):
return str(obj.owner)
def get_meal(self, obj):
print('object of meal',obj)
restaurant = Restaurant.objects.get(slug=str(obj.slug))
meal_qs = restaurant.meal_set.filter(available=True)
meal = MealSerializer(meal_qs, many=True).data
return meal
我的API现在看起来像这样
"meal": [
{
"id": 1,
"meal_category": {
"id": 1,
"name": "veg",
"slug": "veg"
},
"name": "Mushroom drumstick",
"slug": "mushroom-drumstick",
},
{
"id": 2,
"meal_category": {
"id": 2,
"name": "Non-veg",
"slug": "non-veg"
},
"name": "Ham Cheesy Burger",
"slug": "ham-cheesy-burger",
"restaurant": 1
}
],
"name": "Kathmandu Fast Food Center",
"slug": "kathmandu-fast-food-center",
但是我想要这样的饭菜
{
"id":1,
"name":"kathmandu fast food center",
"slug": "kathmandu-fast-food-center",
"meal_category":[
{
"Non veg":[
"meal":[
{
"name":"Ham Burger"
},
{
"name":"Chicken BBQ"
}
]
],
"Veg":[
"meal":[
{
"name":"mushroom soup"
},
{
"name":"Aloo Drumstick"
}
]
]
}
]
}
请指导我如何设计此类API。