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()
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__'
在序列化器和视图之后,当我浏览输入销售时,我得到了它。
答案 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