В настоящее время я получаю следующий ответ из-за вложенного сериализатора. У меня есть вложенный сериализатор продукта внутри сериализатора корзины. Делая так, я получаю следующий результат. Но нужно все атрибуты товара в главном разделе (вне товара, как показано ниже)
{
"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,
)
serializers.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)