【问题标题】:Generate unique ascending numerical id in django model field在 django 模型字段中生成唯一的升序数字 id
【发布时间】:2020-02-17 17:01:24
【问题描述】:
Class Car(models.Model):
     type = models.CharField('Type', max_length=100)
     code = models.CharField('Code', max_length=10, blank=True, null=True)

考虑到我想根据类型列出汽车。我有一个模型和字段,如上面的代码, 我想根据汽车的类型使代码唯一地递增。例如,如果使用类型字段为“HD”创建汽车实例,则代码将为“HD-0000001”。使用 HD 类型创建的下一个模型也是 HD-0000002,依此类推。如果给出了另一种类型,它将保存为“类型”+“最后保存的数字+1”。

我知道我必须在 save() 函数中做一些事情,但我不知道如何根据不同的类型使其唯一。

我们将不胜感激任何建议。 谢谢!

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    也许你可以这样写你的类:

    Class Car(models.Model):
        type = models.CharField('Type', max_length=100)
        code = models.IntegerField('Code', default=-1)
    
        def save(self, *args, **kw):
            if self.code == -1:
                max_code=Car.objects.filter(type=self.type).aggregate(max_code=Max('code'))
                self.code = max_code.get('max_code',0)+1 if max_code else 1
            return super(Car, self).save(*args, **kw)
    
        class Meta:
            unique_together = ('type', 'code')
    

    所以,你永远不应该保存属性代码,因为在第一次保存对象之前,先获取它的类型的最后一个代码号,然后将 self 'code' 设置为 de next 值。

    【讨论】:

    • 我认为这正是我想要的。谢谢。
    猜你喜欢
    • 2013-05-31
    • 2018-04-21
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多