>我有4个型号类别,供应商,位置,产品。供应商属于类别模型(供应商是类别的外键(。其余型号位于供应商(位置、产品(下
ProductSerializer 和 LocationSerializer 嵌套到 VendorSerializer,VendorSerializer 嵌套到CategorySerializer。
class ProductSerializer(WritableNestedModelSerializer):
class Meta:
model = Product
fields = ['id', 'item_name', 'price']
read_only_fields = ['id']
class LocationSerializer(WritableNestedModelSerializer):
class Meta:
model = Location
fields = ['place']
class VendorSerializer(WritableNestedModelSerializer):
vendor_location = LocationSerializer()
product = ProductSerializer(many=True)
class Meta:
model = Vendor
fields = ['vendor_name','vendor_location','product']
read_only_fields = ['id']
class CategorySerializer(WritableNestedModelSerializer):
vendor = VendorSerializer(many=True)
class Meta:
model = Category
fields = ['id', 'category_name', 'tittle', 'vendor']
read_only_fields = ['id']
# 查看
class ProductView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request, format=None, *args, **kwargs):
products = Category.objects.all()
serializer = CategorySerializer(products, many=True, context={'request': request})
return Response({'response': 'ok', 'result': serializer.data})
# 输出
{
"response": "ok",
"result": [
{
"id": 1,
"category_name": "Cake",
"tittle": "test title",
"vendor": [
{
"vendor_name": "Test_Name",
"vendor_location": {
"place": "Test_Place"
},
"product": [
{
"id": 1,
"item_name": "test_1",
"price": 3200,
},
{
"id": 2,
"item_name": "test_2",
"price": 2010,
}
]
}
]
}
]
}
# 预期输出
{
"response": "ok",
"result": [
{
"id": 1,
"category_name": "Cake",
"tittle": "test title",
"vendor": [
{
"vendor_name": "Test_Name",
"vendor_location": {
"place": "Test_Place"
},
"product": [
{
"id": 1,
"item_name": "test_1",
"price": 3200,
}
]
}
]
},
{
"id": 1,
"category_name": "Cake",
"tittle": "test title",
"vendor": [
{
"vendor_name": "Test_Name",
"vendor_location": {
"place": "Test_Place"
},
"product": [
{
"id": 2,
"item_name": "test_2",
"price": 2010,
}
]
}
]
}
]
}
在我的输出中,列出了两个产品。可能不止两个。我只需要产品下的一个产品。所有产品必须以与我在预期输出中提到的相同结构打印。我该怎么做?可能吗?有人可以帮我做到这一点吗?
您可以修改此行:
# old:
products = Category.objects.all() # definately these are not products
# new:
products = Product.objects.values_list('id', flat=True) # get all products ids
categories = Category.objects.filter(vendor__product__in=products)
并将categories
发送给CategorySerializer
,认为这仍然不是您想要的,因为每个重复的类别都将包含有关所有产品(而不仅仅是一个(的信息。
从现在开始,我会去哪里?我会在VendorSerializer
中创建方法get_product
,并以某种方式保存我们现在所处的Category
/Vendor
的信息,如果我们已经为此Category
添加了Product
- 我会跳过接下来添加。
附言。我仍然不明白为什么你需要这种格式。