简体   繁体   中英

writable create() method in drf serializers

models.py

class Product(models.Model):
    product_name = models.CharField(max_length=32)
    quantity = models.IntegerField()
    remarks = models.TextField(blank=True)

class Vendor(models.Model):
    vendor_name = models.CharField(max_length=50)
    address = models.CharField(max_length=100)
    bill_no = models.CharField(max_length=8)
    product = models.ManyToManyField(Product)

serializers.py

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class VendorSerializer(serializers.ModelSerializer):
    product = ProductSerializer(many=True, read_only=False)
    class Meta:
        model = Vendor
        fields = '__all__'

views.py

from rest_framework import viewsets

class VendorViewset(viewsets.ModelViewSet):
    serializer_class = VendorSerializer
    queryset = Vendor.objects.all()

How do I override writable create() method on VendorSerializer to add products details to vendors where products are from the related to Vendor?

您可以覆盖内置的序列化器create方法,但是在pre_save信号中处理对象本身可能更有意义,这样便可以访问ManyToMany对象字段。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM