Home > Software design >  How can I override Django Model's save() method
How can I override Django Model's save() method

Time:09-30

I have a model which looks like this.

import uuid

from django.db import models


class TemplateId(models.Model):

    id = models.SmallAutoField(primary_key=True, serialize=False, verbose_name='ID')
    template_name = models.CharField(max_length=255, default="")
    template_id = models.UUIDField(max_length=255, default=uuid.UUID, unique=True)

    def __str__(self):
        return str(self.template_name)

    class Meta:
    ordering = ('-id',)

I have another function/code where I'm calling an API to fetch the template_name and template_id and store it in dB. But every time when I get a response from the API, I want to override the the whole table (everytime deleting old record and then adding the new records)

currently I'm doing this:

def fetch_template_id():
    
    api_response = # calling the API
    for template_id in api_response:
        obj = TemplateId(template_id=template_id["id"], template_name=template_id["name"])
        obj.save()

In order to override, I tried overriding the save method in my TemplateId model as below but it didn't work

def save(self, *args, **kwargs):
    super(TemplateId, self).save(*args, **kwargs)

Since the data gets saved in the model fields by getting the API response, next time when same data is received from the API response, it throws duplicate data error in the dB. How do I override all the dB fields with each API call?

CodePudding user response:

If the objects exists, update it. If it doesn't, create it. def fetch_template_id():

    api_response = # calling the API
    for template_id in api_response:
        try:
            obj = TemplateId.objects.get(template_id=template_id["id"])
            obj.template_name=template_id["name"]
        except:
            obj = TemplateId(template_id=template_id["id"], template_name=template_id["name"])

        obj.save()

CodePudding user response:

If by override you mean update the template_name of a particular template id, you need to change:

    obj = TemplateId(template_id=template_id["id"], template_name=template_id["name"])
    obj.save()

to

     obj = TemplateId.objects.get(id=template_id["id"])
     obj.template_name = template_id["name"]
     obj.save()

Because in your case you are searching for a particular entry with the 2 conditions, but do not change anything when saving it. save method can stay as is, not need to override it

  • Related