如何在 django 中的两个字段中保存元组 itens?

How to save a tuple itens in two fields in django?

提问人:Ozzyx 提问时间:11/10/2023 更新时间:11/10/2023 访问量:26

问:

在django中,我有一个具有这些模型的项目:

class Colorify(models.Model):
    color_code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
    )
    color_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
    )

用户在两个单独的字段中填写了color_code和color_name,这有时会导致填写错误,现在,我正在创建一个带有选项的字段,以便用户可以选择颜色,并且代码将自动填充。但是,在不更改数据库的情况下。 像这样的东西:

class Colorify(models.Model):
    COLOR = (
        ('149', 'Blue'),
        ('133', 'Red'),
        ('522', 'Black'),
    )
    color_select = models.CharField(
        max_length=255,
        choices=COLOR,
    )
    code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
    )
    color = models.CharField(
        max_length=255,
        null=True,
        blank=True,
    )

我不确定是否可以根据用户从元组中选择的颜色以 forms.py 保存,以便“colorify.code”接收元组的代码,“colorify.color”接收相应的颜色名称。但是,我不确定 save() 方法会是什么样子。

或者,如果有一种更简单的方法可以在不更改数据库的情况下解决此问题。

我设想了以下几点:

`

def save(self):
    colorify.name = colorify.color_select.value
django 模型 django 表单

评论


答:

0赞 Mahammadhusain kadiwala 11/10/2023 #1

颜色 = (('149', '蓝色'),('133', '红色'),('522', '黑色'),)tupel 的这个 tupel 实际上是 python 字典的项目,因此,您可以使用 dict() 在字典中转换它

models.py

class Colorify(models.Model):
    COLOR_CHOICES = [
        ('149', 'Blue'),
        ('133', 'Red'),
        ('522', 'Black'),
    ]

    color_select = models.CharField(
        max_length=255,
        choices=COLOR_CHOICES,
    )
    code = models.CharField(
        max_length=255,
        null=True,
        blank=True,
    )
    color = models.CharField(
        max_length=255,
        null=True,
        blank=True,
    )
    

    def save(self, *args, **kwargs):
        # Get the selected color tuple
        selected_color = dict(self.COLOR_CHOICES).get(self.color_select)
        # print(self.color_select,selected_color)
        if selected_color:
            # Update the 'code' and 'color' fields based on the selected color
            self.code, self.color =self.color_select, selected_color

        super().save(*args, **kwargs)

预览

enter image description here