如果存在相关对象,是否阻止更改字段?

2024-06-10 23:37:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Django应用程序中有两个模型:

class Survey(models.Model):
    survey_type = models.CharField(max_length=1, choices=SURVEY_TYPES)

class Response(models.Model):
    survey = models.ForeignKey(Survey)
    response = models.TextField()

当调查的组织者创建了调查后,他们可以指定类型。一旦第一个响应出现,我不希望组织者能够使用siteadmin来更改类型(因为响应模型中的freetextresponse字段将改变其含义)。你知道吗

我已经研究过使用验证器,但据我所知,它们是用来操作窗体的,而不是要保存的对象。我在它们中找不到任何执行数据库查询的支持。你知道吗

我还研究了重写save方法,但据我所知,save方法不应用于验证(而且我不希望在我的模型中使用任何逻辑)。你知道吗

我在其他框架中这样做的方式是在ORM之上引入一些层,允许我引入业务规则。请告知-这里的最佳做法是什么?你知道吗


Tags: django方法模型应用程序类型modelmodelssave
2条回答

Response模型中的surveyresponse字段设置为唯一 unique together像这样:

class Response(models.Model):
    survey = models.ForeignKey(Survey)
    response = models.TextField()

    class Meta:
        unique_together = (("survey", "response"),)

实际上,您可以使用模型级验证:

class Survey(models.Model):
    survey_type = models.CharField(max_length=1, choices=SURVEY_TYPES)

    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)
        self._old_survey_type = self.survey_type

    def clean(self):
        if (self.survey_type != self._old_survey_type) \
                and survey_typeself.response_set.exists():
            raise ValidationError('Cannot modify the type of a started survey') 

但是要小心,保存对象时不会自动调用Model.clean。当一个ModelForm得到验证(因此也是在admin中)时,它会这样做,但否则您必须检查它是否得到验证或自己调用它。你知道吗

相关问题 更多 >