'The response content must be rendered before it can be iterated over. Django Rest Framework
I have a Cart model and Cartserializers. I am trying to do that is if cart defects exist in the cart and then update the cart by increasing the quantity of cart. I tried a lot to do this. But it raises an error every time this time is The response content must be rendered before it can be iterated over.
Here is my code :)
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']
Solution 1:[1]
Your get_queryset() method must return a queryset!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | shacker |