mardi 27 novembre 2018

Django : Custom save method with queryset

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

Aucun commentaire:

Enregistrer un commentaire