Ian
Ian

Reputation: 351

create() method override in django rest

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

And after serializers and views I get that when i browse to input sell.

  1. How do I automatically connect Customer object to Sell so that I dont need to select the customers objects? Using token or any idea?
  2. Also how to override create() method on customer serializer to add products details from customer view?enter image description here

Upvotes: 0

Views: 4756

Answers (1)

neverwalkaloner
neverwalkaloner

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

Related Questions