【问题标题】:How to autofill a field with concatenated other fields Django如何使用连接的其他字段 Django 自动填充字段
【发布时间】:2021-05-25 20:52:43
【问题描述】:

这是我第一次在这里提出问题,如果不完美,请见谅。

我正在使用 django 开发最新版本。

我想在提交表单时自动生成一个字段(KEY(将在对话框流中使用))值,并将其他字段串联为

KEY =  'SENT_' + search_categories + '_' + '001'

我希望“001”也能自动递增。

我无法显示更多代码,因为我不确定这是否合法,因为我在一家私人公司工作,但我认为我可以在我的 django 模型中显示密钥声明。

key = models.CharField(max_length=30, blank=False, null=False, unique=True)

希望你能帮助我!

非常感谢!

【问题讨论】:

    标签: django database field autofill auto-generate


    【解决方案1】:

    您可以在模型的save 函数中生成密钥:

    class Model(models.model):
        key = models.CharField(max_length=30, blank=False, null=False, unique=True)
        # other attributes...
    
        def save(self, *args, **kwargs):
            # Only generate key on creating if it was not provided
            if not self.id and not self.key:
                # Get your counter and increment it
                counter = 0
                counter += 1
                # Get search_categories (I don't know what it is)
                search_categories = '?'
                # Use f-string to concatenate the key and add zero pad on the counter
                self.key = f'SENT_{search_categories}_{counter:03}'
            super().save(*args, **kwargs)
    

    【讨论】:

    • 我不明白在我的代码中如何调用或在何处调用此函数:/ 'counter:03' 是什么意思?这允许自动增加密钥? AS SENT_001 SENT_002 SENT_003 ?
    • 它应该在包含key 字段的模型定义中。我建议您覆盖 save 函数,但如果您愿意,可以在其他地方使用该逻辑。
    • counter:03 表示计数器(它是一个 int)将被零填充。所以 1 --> 001 ; 54 --> 054.
    • 我唯一不知道的是你的 search_categories 变量,你没有告诉它是什么。
    • 不,我更理解你的回答,我想自己成功。然后,我删除了条件“if not self.id”并输入了“counter = Sentence.objects.count()”。您的回答非常全面且很有帮助。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2012-02-12
    • 1970-01-01
    • 2020-11-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多