Ad

Django : Custom Save Method With Queryset

- 1 answer

I'm trying to create a custom save method in my model and I would like to get your help in order to improve this one.

I'm generating a unique code based on some variables in my form. I generate the code and I make a research before to save it. If another document already gets this code, I generate another one, else I save the object.

This is my save() method in my models.py file :

def save(self, *args, **kwargs):
    import random
    self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}"
    document = Document.objects.filter(code=self.code)
    if document:
        self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}"
    super(Document, self).save(*args, **kwargs)

I think it could me improved, by while instead of if condition.

What do you think about it ?

Thank you

Ad

Answer

I use a while to check if my code is unique, it's quite self explanary and i modified for your code purpose :

def _get_unique_code(self):
    """

    To be used only once in the save method. It creates the unique code.

    """
    import random
    self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}"
    while Document.objects.filter(code=self.code).exists():
        self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}-{random.randint(1,10001)}"
    return self.code

def save(self, *args, **kwargs):
    if not self.code:
        self.code = self._get_unique_code()
    super(Document, self).save()
Ad
source: stackoverflow.com
Ad