Aditya Kushwaha
Aditya Kushwaha

Reputation: 21

Problem on calling save() for post in django rest framework

Calling save() on a serializer is returning below error:

Original exception was:
Traceback (most recent call last):
File "C:\Users\aditya\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\rest_framework\serializers.py", line 940, in create

instance = ModelClass.objects.create(**validated_data)
File "C:\Users\aditya\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\aditya\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
TypeError: save() got an unexpected keyword argument 'force_insert'

views.py

def post(self,request):
    if request.method=='POST':
        serializer = invoiceSerializers(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

model.py

class invoice(models.Model):
    customer = models.CharField(max_length=256, blank=False)
    date = models.DateField(default=now)
    invoice_number = models.IntegerField(editable=False,default=1)
    total_quantity = models.DecimalField(max_digits=10, decimal_places=2)
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)
    total_tax = models.DecimalField(max_digits=10, decimal_places=2)

    def save(self):
        if self._state.adding:
            last_invoice=invoice.objects.all().aggregate(largest=models.Max('invoice_number'))['largest']

            if last_invoice is not None:
                self.invoice_number=last_invoice+1
        super(invoice,self).save()

I am not able to understand why this is happening and how to fix this. Any help is appreciated.

Upvotes: 2

Views: 297

Answers (1)

JPG
JPG

Reputation: 88459

The save() method of Model accepts few keyword arguments such as force_insert,using etc. But, you are not accepting those arguments in your override methods.

So change your save() method as

class invoice(models.Model):
    .....
    .....
    .....
    # your code
    def save(self, *args, **kwargs):
        .....
        .....
        .....
        # your code
        super(invoice, self).save(*args, **kwargs)

Upvotes: 3

Related Questions