在 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
COLOR = (('149', 'Blue'),('133', 'Red'),('522', 'Black'),)
tupel 的 tupel 实际上是 python 字典的项,因此,您可以使用 dict()
将其转换为字典
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)