Python 处理基于其他字段的Django模型字段的需求
这是我正在研究的模型的一个非常简化的版本:Python 处理基于其他字段的Django模型字段的需求,python,django,django-models,Python,Django,Django Models,这是我正在研究的模型的一个非常简化的版本: class ClothingTop(models.Model): SWEATER = 0 SHIRT = 1 TOP_CHOICES = ( (SWEATER, 'Sweat shirt'), (SHIRT, 'Shirt'), ) name = models.CharField(max_length=32) type = models.PositiveSma
class ClothingTop(models.Model):
SWEATER = 0
SHIRT = 1
TOP_CHOICES = (
(SWEATER, 'Sweat shirt'),
(SHIRT, 'Shirt'),
)
name = models.CharField(max_length=32)
type = models.PositiveSmallIntegerField(choices=TOP_CHOICES)
hoodie = models.BooleanField(default=False)
buttons = models.PositiveSmallIntegerField(null=True, blank=True)
def __unicode__(self):
return self.name
@property
def type_text(self):
if self.type == self.SWEATER:
if self.hoodie:
return 'Hooded sweatshirt'
return 'Plain sweatshirt'
elif self.type == self.SHIRT:
return 'Shirt'
如果类型设置为衬衫
,我需要按钮
。我的第一个想法是覆盖save
方法,但我不确定这是否是实现这一点的最明智的方法
有人有什么建议吗?我最简单的建议,我相信这是实践中最好的建议,就是创建一个ClothingTop
ModelForm
,并在表单上设置按钮\u clean()
方法来进行自定义验证。还必须为ClothingTop
ModelAdmin
设置此表单
唯一的其他方法是为按钮
字段创建一个自定义模型字段(验证器在这里不起作用,因为它们只获取按钮字段值,而不知道类型和其他模型字段)。最简单的方法是:
ButtonsField(models.PositiveSmallIntegerField):
def validate(self, value, model_instance):
# here we get the buttons field value and can get the type value
# exactly what we need!
type = getattr(model_instance, 'type')
if type == SHIRT and not value:
raise ValidationError('Type set to shirt, but buttons value is empty')
super(self, ButtonsField).validate(value, model_instance)
为了完整性,我提到了使用自定义字段的方法,我认为您应该跳过创建自定义字段类型,除非它是完全通用的并且可以在任何模型上重用。对于那些特殊情况,只需使用表单验证。您的模型应该只确保数据库的完整性,您已经用ClothingTop
完美地涵盖了这一点,业务规则从表单验证中冒出来。我最简单的建议,我相信这是实践中最好的建议,就是创建ClothingTop
模型表单
,并将按钮设置为干净()
将执行自定义验证的表单上的方法。还必须为ClothingTop
ModelAdmin
设置此表单
唯一的其他方法是为按钮
字段创建一个自定义模型字段(验证器在这里不起作用,因为它们只获取按钮字段值,而不知道类型和其他模型字段)。最简单的方法是:
ButtonsField(models.PositiveSmallIntegerField):
def validate(self, value, model_instance):
# here we get the buttons field value and can get the type value
# exactly what we need!
type = getattr(model_instance, 'type')
if type == SHIRT and not value:
raise ValidationError('Type set to shirt, but buttons value is empty')
super(self, ButtonsField).validate(value, model_instance)
为了完整性,我提到了使用自定义字段的方法,我认为您应该跳过创建自定义字段类型,除非它是完全通用的并且可以在任何模型上重用。对于那些特殊情况,只需使用表单验证。您的模型应该只确保数据库的完整性,您已经用ClothingTop
完美地介绍了这一点,业务规则从表单验证中泡泡而下。使用此解决方案,我还必须为管理员应用程序提供表单,对吗?是的,您需要在ModelAdmin
上设置form=forms.ClothingTopForm
。您需要这样做以确保员工用户受到业务规则的约束。使用此解决方案,我还必须为管理员应用程序提供一个表单,对吗?是的,您需要在ModelAdmin
上有form=forms.ClothingTopForm
。您需要这样做,以确保员工用户受到业务规则的约束。