Python 如何在django rest框架中仅使用特定的变量对象将项添加到愿望列表?

Python 如何在django rest框架中仅使用特定的变量对象将项添加到愿望列表?,python,django,api,django-rest-framework,view,Python,Django,Api,Django Rest Framework,View,之前,我的产品型号不包括变型。现在我添加了与产品模型有很多关系的变体。变体模型由颜色、大小、价格等字段组成。我已经创建了api端点,用于将项目添加到愿望列表中 现在,如果我添加了相同的api,它将包含所有的变体。但是,在前端,用户可以灵活地只选择一个varaint 如何改变这一点 我的模型: class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',),

之前,我的产品型号不包括变型。现在我添加了与产品模型有很多关系的变体。变体模型由颜色、大小、价格等字段组成。我已经创建了api端点,用于将项目添加到愿望列表中

现在,如果我添加了相同的api,它将包含所有的变体。但是,在前端,用户可以灵活地只选择一个varaint

如何改变这一点

我的模型:

    class Variants(models.Model):
        SIZE = (
            ('not applicable', 'not applicable',),
            ('S', 'Small',),
            ('M', 'Medium',),
            ('L', 'Large',),
            ('XL', 'Extra Large',),
        )
        AVAILABILITY = (
            ('available', 'Available',),
            ('not_available', 'Not Available',),
        )
        price = models.DecimalField(decimal_places=2, max_digits=20,blank=True,null=True)
        size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True)
        color = models.CharField(max_length=70, default="not applicable",blank=True,null=True)
        quantity = models.IntegerField(default=10,blank=True,null=True)  # available quantity of given product
        vairant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available')
    
        class Meta:
            verbose_name_plural = "Variants"
    
    
    class Product(models.Model):
        AVAILABILITY = (
            ('in_stock', 'In Stock',),
            ('not_available', 'Not Available',),
            )
        WARRANTY = (
            ('no_warranty', 'No Warranty',),
            ('local_seller_warranty', 'Local Seller Warranty',),
            ('brand_warranty', 'Brand Warranty',),
        )
        SERVICES = (
            ('cash_on_delivery', 'Cash On Delivery',),
            ('free_shipping', 'Free Shipping',),
        )
        
        category = models.ManyToManyField(Category, blank=False)
        brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
        collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
        featured = models.BooleanField(default=False)  # is product featured?
        best_seller = models.BooleanField(default=False)
        top_rated = models.BooleanField(default=False)
        tags = TaggableManager(blank=True)  # tags mechanism
        name = models.CharField(max_length=150)            
        picture = models.ManyToManyField(ImageBucket,null=True,blank=True)
        availability = models.CharField(max_length=70, choices=AVAILABILITY, default='in_stock')
        warranty = models.CharField(max_length=100, choices=WARRANTY, default='no_warranty')
        services = models.CharField(max_length=100, choices=SERVICES, default='cash_on_delivery')
        variants = models.ManyToManyField(Variants,blank=True,null=True,related_name='products')

    class Meta:
        ordering = ("name",)

    def __str__(self):
        return self.name

class WishListItems(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE,blank=True)
    #wishlist = models.ForeignKey(WishList,on_delete=models.CASCADE, related_name='wishlistitems')
    item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True)
我的看法:

class AddtoWishListItemsView(CreateAPIView,DestroyAPIView):
    permission_classes = [IsAuthenticated]
    queryset = WishListItems.objects.all()
    serializer_class = WishListItemsTestSerializer

    def perform_create(self, serializer):
        user = self.request.user
        if not user.is_seller:
            item = get_object_or_404(Product, pk=self.kwargs['pk'])
            serializer.save(owner=user, item=item)
        else:                
            raise serializers.ValidationError("This is not a customer account.Please login as customer.")


    def perform_destroy(self, instance):
        instance.delete()
我的序列化程序:

class WishListItemsTestSerializer(serializers.ModelSerializer):    
    class Meta:
        model = WishListItems
        fields = ['id','item']
        depth = 2
我的网址:

path('api/addwishlistitems/<int:pk>', views.AddtoWishListItemsView.as_view(),name='add-to-wishlist'),
path('api/addwishlistitems/',views.AddtoWishListItemsView.as_view(),name='add-to-wishlist'),

我认为您需要在模型
WishListItems
中添加变量

您需要从开始序列化“父”模型
产品
,如下所示:

from rest_framework import serializers


class VariantSerializer(serializers.ModelSerializer):    

    class Meta:
       model = Variant
       fields = "__all__"


class ProductSerializer(serializers.ModelSerializer):    
    variants = VariantSerializer(many=True, read_only=True)

    class Meta:
       model = Product
       fields = "__all__"


class WishListItemsTestSerializer(serializers.ModelSerializer): 
    item = ProductSerializer(read_only=True)

    class Meta:
        model = WishListItems
        fields = ['id','item', 'variant']

奖金!。如果您希望简化以填充相关变量,可以从drf_writable_nested import writable nested ModelSerializer使用此


你读过这个吗?我在不同的应用程序中有一个名为order的wishlits模型。因此,orderserializer中无法识别产品和变体的序列化程序。我已导入序列化程序,但无法识别此variants=VariantSerializer(many=True,read_only=True),即不建议使用many=True。能否显示更多“顺序”代码?
from rest_framework import serializers
from drf_writable_nested import WritableNestedModelSerializer


class VariantSerializer(serializers.ModelSerializer):    

    class Meta:
       model = Variant
       fields = "__all__"


class ProductSerializer(WritableNestedModelSerializer):    
    variants = VariantSerializer(many=True)

    class Meta:
       model = Product
       fields = "__all__"


class WishListItemsTestSerializer(serializers.ModelSerializer): 
    item = ProductSerializer()

    class Meta:
        model = WishListItems
        fields = ['id','item', 'variant']