Home > Software design >  DRF is not updating the database
DRF is not updating the database

Time:02-13

Here's the model:

from django.db import models
from datetime import datetime, timedelta


# Create your models here.

def set_expiration():
    return datetime.today().date()   timedelta(days=30)


class Customer(models.Model):
    email = models.EmailField(max_length=254, unique=True)
    created_on = models.DateField(auto_now_add=True)
    expires_on = models.DateField(editable=False, default=set_expiration())

    def __str__(self):
        return self.email

And this is the view:

@api_view(['POST'])
def update_customer(request):
    try:
        customer = Customer.objects.get(email=request.data['email'])
    except ObjectDoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = CustomerSerializer(instance=customer, data=request.data)

    if serializer.is_valid(raise_exception=True):
        serializer.save()

    return Response(serializer.data)

And the serilizer:

from rest_framework import serializers
from .models import Customer


class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

At this moment I have a record in database with expires_on set to 2022-03-14 and I want to update that to 2024-12-12 so I call the endpoint with the following data:

{
    "email": "[email protected]",
    "expires_on": "2024-12-12"
}

The view returns this:

{
    "id": 1,
    "email": "[email protected]",
    "created_on": "2022-02-12",
    "expires_on": "2022-03-14"
}

This is the existing data. expires_on is not updated with the new value.

I get no error and no exception. It just doesn't work.

CodePudding user response:

Remove editable=False from expires_on field.

class Customer(models.Model):
    email = models.EmailField(max_length=254, unique=True)
    created_on = models.DateField(auto_now_add=True)
    expires_on = models.DateField(default=set_expiration())

    def __str__(self):
        return self.email
  • Related