【发布时间】:2018-11-27 08:43:58
【问题描述】:
我正在尝试在我的模型中创建一个custom save method,我希望得到您的帮助以改进它。
我正在根据form 中的一些变量生成unique code。我生成代码并在保存之前进行研究。如果另一个文档已经获取了此代码,我将生成另一个,否则我保存该对象。
这是我的 models.py 文件中的 save() 方法:
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)
我认为它可以通过while 而不是if 条件来改进。
你怎么看?
谢谢
【问题讨论】:
-
while循环如何比单个if条件更有效? -
因为如果
if语句中的self.code已经存在于我的数据库中?我需要循环直到我得到一个唯一的self.code。也许这不是while循环,我必须改进我的if? -
好吧,这不是
efficient代码。那是correct代码。你在这里所做的实际上是不正确的。
标签: python django if-statement while-loop