Reputation: 351
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__'
And after serializers and views I get that when i browse to input sell.
Upvotes: 0
Views: 4756
Reputation: 47354
If you need to pass customer to the sell serializer automaticaly. You can pass it to the serializer's save method in the view:
serializer.save(customer=request.user)
You need to exclude customer
field from serializer:
class SellSerializer(serializers.ModelSerializer):
class Meta:
model = Sell
exclude = ('customer',)
To save nested product
you can save all new products to the list and then pass this list to the product.add()
method:
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
Upvotes: 2