Home > Software engineering >  Django Rest Framework - overriding save in backend is not creating custom id
Django Rest Framework - overriding save in backend is not creating custom id

Time:12-10

I am working on a project. I have Django for my backend and Vue for my front end. When using the templates and saving in the Django project I have no issues.

However, when I POST to my projects API the following save from my modal is not being created.

models.py

class DevProjects(models.Model):
    PROJECT_TYPE = [
        ('New Application', 'New Application'),
        ('Update Application', 'Update Application'),
        ('Bug Fixes', 'Bug Fixes')
    ]
    PROJECT_STATUS = [
        ('New', 'New'),
        ('In Progress', 'In Progress'),
        ('Complete', 'Complete'),
    ]
    project_id = models.CharField(max_length=15, editable=False, unique=True)
    project_title = models.CharField(max_length=100)
    project_desc = models.CharField(max_length=500)
    project_category = models.CharField(max_length=25, choices=PROJECT_TYPE, null=True, blank=True)
    project_status = models.CharField(max_length=25, choices=PROJECT_STATUS, default='New')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)
    created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        super(DevProjects, self).save(**kwargs)
        self.project_id = 'PROJ-'   str(self.id)
        super(DevProjects, self).save(**kwargs)

    def __str__(self):
        return self.project_title

I have the project_id being created on save which gets the original ID but just adds 'PROJ-' in front. Whenever I submit the form from my frontend, that save definition is not being called, thus not creating the project_id.

Project ID is what I use to send a GET request to get the projects.

serailizers.py

class DevProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = DevProjects
        fields = ("project_id", "project_title", "project_desc", "project_category", "project_status")

views.py

class DevProjectViewSet(viewsets.ModelViewSet):
    serializer_class = DevProjectSerializer
    queryset = DevProjects.objects.all()

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

Whenever I post, I get the following error:

IntegrityError: UNIQUE constraint failed: ckcSupportWeb_devprojects.project_id

What do I need to do for the project_id to generate when POSTing from DRF? Any and all help is appreciated.


UPDATE

I can try to use the following code in my viewset:

def create(self, *args, **kwargs):
        self.project_id = 'PROJ-'   str(self.id)
        super(DevProjectViewSet, self).save(**kwargs)

But, I get the following error:

self.project_id = 'PROJ-'   str(self.id)
AttributeError: 'DevProjectViewSet' object has no attribute 'id'

I am truly stuck on how to handle this for API post requests.

CodePudding user response:

From what I can understand, you can relax the unique constraint on the project_id and your previous code should work fine.

Since the project code is not editable, it won't be updated from a POST API call.

CodePudding user response:

I was able to get rid of all of these issues with writing a simple function in utils.py that gets the latest ID created, adds 1 and then sets the new project_id.

CodePudding user response:

Try with this code snippet

def save(self, *args, **kwargs)
    self.project_id = 'PROJ-'   str(self.id)
    super(DevProjects, self).save(**kwargs)
  • Related