django 如何使模型保存方法的PK增加n个数字

4sup72z8  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(132)

这是我之前的post的后续问题。
我正在尝试覆盖model的保存方法,以便主键按5递增,如下所示:

class Client(Model):
    client_id= models.PositiveIntegerField(primary_key=True)
    client_name = models.CharField(max_length=1000, null=True, blank=True)

    
    # Overwrite the Save functionality to increment the Client ID by 5
    def save(self, *args, **kwargs):
        try:
            if self._state.adding is True:
                # Intialize the first Client Id to 5 and then after Increment by 5
                if not Client.object.count():
                    self.client_id = 5
                else:
                    self.client = Client.object.last().client_id + 5
                super(Client, self).save(*args, **kwargs)
        except (Exception, FileNotFoundError, IOError, ValueError) as e:
            print(e)
            return False
    
    def __str__(self):
        return str(self.client_name)

    class Meta:
        db_table = 'Client'

然而,上面的代码不起作用,事实上它根本没有创建客户端条目。
你觉得我哪里做错了吗?
谢谢你,谢谢你

ulydmbyx

ulydmbyx1#

在else部分中,您没有指定client_id.添加以下代码:

if not Client.object.count():
    self.client_id = 5
else:
    self.client_id = Client.object.last().client_id + 5

相关问题