代码如下
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 会报错
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.