如何在 django rest 框架中仅使用特定变体对象将项目添加到愿望清单?

Posted

技术标签:

【中文标题】如何在 django rest 框架中仅使用特定变体对象将项目添加到愿望清单?【英文标题】:How to add item to wishlist with only specific variant object(s) in django rest framework? 【发布时间】:2021-03-09 09:21:11 【问题描述】:

在我的产品模型不包含变体之前。现在我添加了与产品模型的多对多关系的变体。变体模型由颜色、尺寸、价格等字段组成。我已经创建了 api endpoints 用于将项目添加到愿望清单。

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

如何改变这个?

我的模型:

    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'),

【问题讨论】:

你读过这个吗? ***.com/questions/33182092/… 【参考方案1】:

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

你需要从序列化“父亲”模型Product开始,像这样:

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 documentation

奖金!。如果您想简化以填充相关变体,可以使用此from drf_writable_nested import WritableNestedModelSerializerdrf writable

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']

【讨论】:

我在名为 order 的不同应用程序中有愿望灯模型。因此,orderserializer 无法识别产品和变体的序列化程序。我已经导入了序列化程序,但是这个变量 = VariantSerializer(many=True, read_only=True) 无法识别,即不建议使用 many=True。

以上是关于如何在 django rest 框架中仅使用特定变体对象将项目添加到愿望清单?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 django 中仅获取表的特定列? [复制]

如何在 django rest 框架中的嵌套序列化器相关对象上使用 prefetch_related?

Django rest框架将POST数据分配给特定用户

django rest框架在nginx后面但不直接给出403

如何在 Django REST 框架中使用事务?

如何在 django rest 框架中访问获取请求数据