【问题标题】:unique id generator in a custom format in djangodjango中自定义格式的唯一ID生成器
【发布时间】:2020-12-06 09:16:18
【问题描述】:

我想在我的模型中生成一个唯一的 id 代码 例如 -

id want to generate

任何人都可以帮助我吗? 我想要表格中的id,如下图-

class parameter(models.Model)
  name=models.models.CharField(max_length=50)
  type=model.#should come from another table
  subtype=model.#should come from another table 
  id= # should compile all the above as in picture

谢谢

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    我认为你不应该将唯一id存储在数据库中,因为你可以通过属性方法轻松生成它:

    class Parameter(models.Model)
      name=models.models.CharField(max_length=50)
      type=model.ForeignKey(Type)
      subtype=model.ForeignKey(SubType)
      product_type=model.ForeignKey(ProductType)
      serial_no = models.CharField()
    
      @property
      def generated_id(self):
          return '{}/{}/{}/{}'.format(self.type_id, self.subtype_id, self.product_type_id, self.serial_no.zfill(2))
    

    如果您打算在admin site 中显示它,那么只需像这样尝试:

    @admin.register(Parameter)
    class ParameterAdmin(admin.ModelAdmin):
        model = Parameter
        fields = ['type', 'sub_type', 'product_type', 'serial_no', 'generated_id']
        readonly_fields = ('generated_id',)
    

    更新

    如果你想存储在数据库中,那么你需要覆盖模型的保存方法。像这样:

    class Parameter(models.Model)
      name=models.models.CharField(max_length=50)
      type=model.ForeignKey(Type)
      subtype=model.ForeignKey(SubType)
      product_type=model.ForeignKey(ProductType)
      serial_no = models.CharField()
      generated_id = models.CharField()
    
      def generate_id(self):
          return '{}/{}/{}/{}'.format(self.type_id, self.subtype_id, self.product_type_id, self.serial_no.zfill(2))
    
      def save(self, *args, **kwargs):
         self.generated_id = self.generate_id()
         super().save(*args, **kwargs)
    

    【讨论】:

    • 如果我们使用属性方法生成,我们可以使用它来过滤或软件中的其他任何地方
    • 只要可以访问对象,就可以在任何地方使用属性方法。但它不适用于查询集。因此过滤将不起作用。但是由于这个唯一 ID 是基于其他字段生成的,您可以使用这些字段进行过滤并最终找到具有该唯一 ID 的对象
    • 如果我想在数据库中存储我应该去做什么?
    • 示例我们有 10 个序列号,后来我删除了一个。所以现在我生成的 id 也会被改变吗?我们怎样才能避免这种情况
    • 只要name、type、product type等保持一致,生成的id应该一致
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多