返回

必须先呈现响应内容,然后才能对其进行迭代.Django Rest框架

发布时间:2022-04-20 08:35:27 419
# django# 缺陷

我有一个 Cart 模型和 Cartserializers。我正在尝试这样做,如果购物车中存在购物车缺陷,然后通过增加购物车的数量来更新购物车。我尝试了很多来做到这一点,但是每次这个时候都会报错是必须先渲染响应内容才可以迭代。

这是我的代码:)

views.py*

class CartViewSet(viewsets.ModelViewSet):
    serializer_class = CartSerializer
    permission_classes = (IsAuthenticated,)
    def get_queryset(self):
        user = self.request.user
        if user.is_authenticated:
            if user is not None:
                if user.is_active and user.is_superuser or user.is_Customer:
                    return Cart.objects.all()
                raise PermissionDenied()
            raise PermissionDenied()
        raise PermissionDenied()
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['date_created', 'user']
    @action(detail=False)
    def count(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        count = queryset.count()
        content = {'count': count}
        return Response(content)
        
    def create(validated_data, get):
        quantity, created = Cart.objects.update_or_create(
            user = validated_data.get('user', None),
            defects=validated_data.get('defects', None),
            defaults={'quantity': validated_data.get('quantity' + str(1), None)})
        return quantity
        if quantity is created.create:
            return Response ({
                'status' : True,
                "detail" : "created"
            })
        if quantity is created.update:
            return Response ({
                'status' : True,
                "detail" : "updated"
            })

models.py

from django.db import models
from accounts.models import User, SubCategory

# Create your models here.

class Cart(models.Model):
    user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL)
    quantity = models.IntegerField(default=1)
    service = models.ForeignKey('accounts.SubCategory',null=True,  on_delete=models.SET_NULL)
    defects = models.ForeignKey('Defects',null=True,  on_delete=models.SET_NULL)
 
    price = models.IntegerField(default=False)
    date_created = models.DateTimeField(auto_now_add=True)
    total = models.IntegerField(blank=True, null=True)    

    def __str__(self):
        return self.user.username

serializers.py

from rest_framework import serializers
class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ['id','url', 'user', 'service', 'defects', 'date_created', 'quantity' , 'price', 'total']
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(1)
按点赞数排序
用户头像