1

Is there any way to get default value (such as ID of type UUID) after creating a new row.

Here is my model

class Employee(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name= models.CharField(max_length=255)
    created_at = models.DateField(default=None, blank=True, null=True)
    class Meta:
        db_table="business"

When I create I do this, for example

from rest_framework import generics
from django.forms.models import model_to_dict

class Create(generics.CreateAPIView):
    def post(self, request)
        inputData = {"name":"abcdef", "created_at": datetime.datetime.now}
        employee = Employee.objects.create(**inputData)    
        return JsonResponse(model_to_dict(employee), safe=False)

Here is the response:

{
    "name": "abcdef",
    "created_at": "2022-05-24T10:36:39.126",
}

So now I dont know what is the ID of the new row I just create

Chau Loi
  • 1,106
  • 1
  • 14
  • 36

1 Answers1

1

It happens because you set id as non-editable. At the same time, model_to_dict returns a dictionary suitable for passing as a Form's initial keyword argument.

You can easily check the source code of model_to_dict, and see that fields with such attribute set are skipped. Check this Convert Django Model object to dict with all of the fields intact it might be helpfull.

funnydman
  • 9,083
  • 4
  • 40
  • 55