代码如下
class FoodApiSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField()
class Meta:
model = Food
fields = ('foodid', 'name', 'info', 'price', 'stock', 'image_url', 'num', 'status')
# imagefield 序列化以获取完整的 URL
def get_image_url(self, Food):
request = self.context.get('request')
request = request['request']
image_url = Food.image.url
return request.build_absolute_uri(image_url)
class CategoryApiSerializer(serializers.ModelSerializer):
foods = serializers.SerializerMethodField()
def get_foods(self, obj):
foods = Food.objects.filter(Q(category=obj.categoryid), Q(status='True'))
if foods is not None and len(foods) > 0:
for x in foods:
return FoodApiSerializer(x, context={"request": self.context}).data
else:
return ''
class Meta:
model = Category
fields = ('categoryid', 'categoryname', 'foods')
read_only_fields = ('categoryid', 'categoryname', 'foods')
def create(self, validated_data):
pass
def update(self, instance, validated_data):
pass
现在 foods 下面的 json,只能显示一条数据,其他都没有 而且只能用 for 来 return FoodApiSerializer(x, context={"request": self.context}).data 或者 FoodApiSerializer(foods[0], context={"request": self.context}).data return FoodApiSerializer(foods, context={"request": self.context}).data 会报错
1
Kaco OP [
{ "categoryid": 1, "categoryname": "特色菜", "foods": { "foodid": 1, "name": "西蓝花炒牛肉 Tr", "info": "西蓝花炒牛肉", "price": 13.99, "stock": 99999, "image_url": "http://0.0.0.0:8000/media/food/2019/09/Recedetangle_21_Copy_8.png", "num": 0, "status": "True" } }, { "categoryid": 2, "categoryname": "小炒", "foods": "" }, { "categoryid": 3, "categoryname": "粥粉面", "foods": "" }, { "categoryid": 4, "categoryname": "汤品", "foods": { "foodid": 3, "name": "人参汤 Tr", "info": "人参汤", "price": 9.82, "stock": 22222, "image_url": "http://0.0.0.0:8000/media/food/2019/09/Rectangle_21_Copy_8.png", "num": 0, "status": "True" } }, { "categoryid": 5, "categoryname": "围餐", "foods": "" } ] 每个 foods 分类下只显示一个菜品,其他都没显示 |
2
imzxk 2019-09-14 22:24:37 +08:00
class CategoryApiSerializer(serializers.ModelSerializer):
foods = serializers.SerializerMethodField() |
3
imzxk 2019-09-14 22:27:08 +08:00
class CategoryApiSerializer(serializers.ModelSerializer):
foods = FoodApiSerializer(many=True) def to_representation(self, instance): #这里过滤试试 |
6
windfarer 2019-09-14 23:20:32 +08:00
for 里面 return 了可不就出来一个东西就结束了
|
9
Kaco OP 已经解决...是我漏了一个参数
return FoodApiSerializer(foods,many=True, context={"request": self.context}).data 加上 many=True 就可以了 |