Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python /cart/'处的类型错误;产品';对象不可下标_Python_Django_Rest_Django Rest Framework_Typeerror - Fatal编程技术网

Python /cart/'处的类型错误;产品';对象不可下标

Python /cart/'处的类型错误;产品';对象不可下标,python,django,rest,django-rest-framework,typeerror,Python,Django,Rest,Django Rest Framework,Typeerror,我正在RESTfulAPI项目中创建购物车模型。对于使用For语句请求的每个产品,我希望保存每个产品,一个请求中的cauz可能会在购物车中显示多个产品。下面是我的 serializers.py: from rest_framework import serializers from main.serializers import ProductDetailsSerializer from main.models import Cart, Product, CartProduct

我正在RESTfulAPI项目中创建购物车模型。对于使用For语句请求的每个产品,我希望保存每个产品,一个请求中的cauz可能会在购物车中显示多个产品。下面是我的

serializers.py: 

    from rest_framework import serializers
from main.serializers import ProductDetailsSerializer
from main.models import Cart, Product, CartProduct


# создаем сериализатор orderproduct
class CartProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = CartProduct
        fields = ('product', 'count')


class CartProductRepresentationSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='product.id')
    title = serializers.CharField(source='product.title')

    class Meta:
        model = CartProduct
        fields = ('id', 'title', 'price', 'count', 'product')


class AddProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('id')


class CartSerializer(serializers.ModelSerializer):
    items = CartProductSerializer(many=True, write_only=True) # здесь мы добавляем этот продукт заказа
    class Meta:
        model = Cart
        fields = ('count', 'items') # передаем все эти поля сюда

    def get_total_cost(self, obj):
        return obj.get_total_cost()
        # здесь мы добавляем total cost (def get_total_cost(self. obj))

    def create(self, validated_data):
        request = self.context.get('request')
        items = validated_data.pop('items')
        cart = Cart.objects.create(**validated_data)
        if request.user.is_authenticated:
            cart.user = request.user
            cart.save()

        for product in items:
            product = product['product']
            # print(product)
            product_id = request.GET.get('product')
            CartProduct.objects.create(cart=cart, product_id=product_id, price=product.price, count=product['count'])
            product.save()

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['user'] = instance.user
        representation['product'] = CartProductRepresentationSerializer(instance.products.all(), many=True, context=self.context).data
        return representation
这是模型。我为购物车和产品之间的m2m字段创建购物车和购物车产品

    models.py

from django.db import models

from account.models import User

class Category(models.Model):
    name = models.CharField(max_length=50 ,unique=True)
    slug = models.SlugField(max_length=50 ,primary_key=True)
    parent = models.ForeignKey('self', related_name='child', blank=True, null=True, on_delete=models.CASCADE)

    def __str__(self):
        if self.parent:
            return f'{self.parent} -> {self.name}'
        return self.name


class Product(models.Model):
    category = models.ManyToManyField(Category)
    title = models.CharField(max_length=250)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    author_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.title


class Comment(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    text = models.CharField(max_length=100)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return f"{self.author}: {self.text}"


class ProductImage(models.Model):
    product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='products', null=True, blank=True)



class Cart(models.Model):
    date_created = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=255, blank=True, null=True, default=False)
    user = models.ForeignKey(User, related_name="carts", on_delete=models.CASCADE, blank=True, null=True)
    count = models.PositiveIntegerField(default=1)


class CartProduct(models.Model):
    product = models.ForeignKey(Product, related_name='products', on_delete=models.CASCADE)
    cart = models.ForeignKey(Cart, related_name='cart', on_delete=models.CASCADE)
    count = models.PositiveIntegerField(default=1)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
这里是views.py,通过使用ModelViewSet,我想列出购物车中的所有产品

views.py

from rest_framework import viewsets
from cart.serializers import CartSerializer
from main.models import Cart


class CartViewSet(viewsets.ModelViewSet):
    model = Cart
    serializer_class = CartSerializer

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