django rest中的create()方法重写

时间:2018-06-09 13:27:52

标签: django django-rest-framework

models.py

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

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

class Sell(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    date = models.DateField(auto_now_add=True)
    total = models.IntegerField()
    vat = models.IntegerField()

serializers.py

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

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

class SellSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sell
        fields = '__all__'

在序列化器和视图之后,当我浏览输入销售时,我得到了它。

  1. 如何自动将Customer对象连接到Sell,以便我不需要选择客户对象?使用令牌或任何想法?
  2. 如何覆盖客户序列化程序上的create()方法以从客户视图添加产品详细信息?enter image description here

1 个答案:

答案 0 :(得分:1)

如果您需要自动将客户传递给销售序列化程序。您可以将其传递给视图中的序列化程序save method

serializer.save(customer=request.user)

您需要从序列化程序中排除customer字段:

class SellSerializer(serializers.ModelSerializer):
    class Meta:
        model = Sell
        exclude = ('customer',)

要保存嵌套product,您可以将所有新产品保存到列表中,然后将此列表传递给product.add()方法:

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

    def create(self, validated_data):
        product_data = validated_data.pop('product')
        customer = Custome.objects.create(**validated_data)
        product_lits = [] 
        for product_details in product_data:                    
            product_list.append(Product.objects.create(**product_details))
        customer.product.add(*product_list)
        return customer