Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DRF is not updating the database

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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": "myemail@mydomain.com",
    "expires_on": "2024-12-12"
}

The view returns this:

{
    "id": 1,
    "email": "myemail@mydomain.com",
    "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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading