Задать вопрос
DoggieMurr
@DoggieMurr
Python Enthusiast

Как сериализовать m2m в DRF?

models.py
class Product(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4)
    title = models.CharField('Title', max_length=255, null=False, blank=False)
    slug = models.SlugField('Slug', unique=True, null=True, blank=True)
    description = models.TextField(null=False, blank=False)
    specification = models.JSONField(null=False, blank=False)
    images = models.JSONField(null=True, blank=True)
    price = models.IntegerField(null=False, blank=False)
    discount = models.IntegerField(null=True, blank=True)
    total_price = models.IntegerField(null=True, blank=True)
    date = models.DateField(auto_now_add=True)
    category = models.ForeignKey('Category',
                                 on_delete=models.CASCADE)
    is_available = models.BooleanField(default=True)

class CartProduct(models.Model):
    product = models.ForeignKey(Product,
                                on_delete=models.CASCADE)
    cart = models.ForeignKey('Cart',
                             on_delete=models.CASCADE)

class Cart(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4)
    products = models.ManyToManyField(Product, null=False, blank=False, through=CartProduct)
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             null=False,
                             blank=False,
                             related_name='cart')


views.py
class CartView(ListAPIView):
    serializer_class = CartSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        return Cart.objects.filter(user=user)


serializer.py
class CartSerializer(ModelSerializer):

    class Meta:
        model = Cart
        fields = '__all__'


response
[
    {
        "id": 1,
        "uuid": "bb07ae98-b6ee-49e6-b40d-52f21e1e8bbf",
        "user": 1,
        "products": [
            4,
            4,
            5
        ]
    }
]


Нужно, что бы получилось
[
    {
        "id": 1,
        "uuid": "bb07ae98-b6ee-49e6-b40d-52f21e1e8bbf",
        "user": 1,
        "products": [
           {
                "id": 4,
                "title": "prod title",
                "total_price": 999,
                "quantity": 2,
                "amount": total_price * quantity
            }
        ],
        "cart_amount": `sum of all products amount`
    }
]
  • Вопрос задан
  • 224 просмотра
Подписаться 1 Простой 1 комментарий
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы