【问题标题】:Django : Custom save method with querysetDjango:使用查询集的自定义保存方法
【发布时间】: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


【解决方案1】:

我使用while 来检查我的代码是否是唯一的,这很容易解释,我为您的代码目的进行了修改:

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()

【讨论】:

  • 对我来说是的,它工作正常!非常感谢:)
【解决方案2】:

我假设 save() 方法是模型 Document 并且我认为 self.code 将始终是唯一的(因为 pub_id 和 randomint)所以 if/while 对我来说看起来没有必要。

【讨论】:

    【解决方案3】:

    您获得数据库中已经存在的匹配代码的概率至少可以说是百万分之一。

    话虽如此,这就是您可能一直在寻找的while

    import random
    def get_code(self):
        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_code()
        super(Document, self).save()
    

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 2011-11-29
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多