【发布时间】:2019-03-26 05:14:29
【问题描述】:
由于嵌套的序列化程序,目前我得到了以下响应。我在购物车序列化程序中嵌套了产品序列化程序。通过这样做,我得到以下结果。但是想要产品的所有属性在主区(产品外,如下图)
{
"product": {
"id": 1,
"name": "Ghost Peanut Butter Cereal Milk Whey Protein",
"product_code": "B07FLJYP5M",
"description": "Ghost products feature a 100% transparent label that fully discloses the dose of each active ingredient.",
"price": "5000.00",
"photo": "https://images-na.ssl-images-amazon.com/images/I/61WZazUpWsL._SX522_.jpg",
"link_to_amazon": "https://www.amazon.com/dp/B07FLJYP5M/?tag=1230568-20"
},
"description": null,
"default": "Yes"
}
但我想要如下回复:
{
"name": "Ghost Peanut Butter Cereal Milk Whey Protein",
"product_code": "B07FLJYP5M",
"description": "Ghost products feature a 100% transparent label that fully discloses the dose of each active ingredient.",
"price": "5000.00",
"photo": "https://images-na.ssl-images-amazon.com/images/I/61WZazUpWsL._SX522_.jpg",
"link_to_amazon": "https://www.amazon.com/dp/B07FLJYP5M/?tag=1230568-20",
"description": null,
"default": "Yes"
}
models.py
class DefaultCart(models.Model):
# Default Cart in Model class
YES = 'Yes'
NO = 'No'
DEFAULT_CHOICES = (
(YES, 'Yes'),
(NO, 'No'),
)
product = models.ForeignKey(Product, related_name='product', on_delete=models.CASCADE)
description = models.TextField(blank=True, null=True)
default = models.CharField(
max_length=3,
choices=DEFAULT_CHOICES,
default=YES,
)
序列化器.py
class ProductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Product
fields=(
'id','name','product_code','description','price','photo','link_to_amazon'
)
class DefaultCartSerializer(serializers. HyperlinkedModelSerializer):
product = ProductSerializer(read_only=True)
class Meta:
model = DefaultCart
fields = (
'product',
'description',
'default'
)
read_only_fields = ('id',)
views.py
def index(request):
# retrive all default_carts or create new default_cart
if request.method == 'GET':
default_carts = DefaultCart.objects.all()
serializer = DefaultCartSerializer(default_carts, many=True)
return Response(serializer.data)
【问题讨论】:
-
请添加视图和序列化程序
-
这里我已经更新了。
-
同时添加你的 mode.py
-
这里我添加了我的模型
标签: django-rest-framework serialization