Django admin.py 尝试保存 manytomany 字段时出现 ValueError
Django admin.py ValueError when trying to save manytomany field
我正在尝试在 Django 中创建一个带有 manytomany 字段的模型,并使用默认的 admin.py 接口我收到一个 ValueError:需要在这么多之前为字段 "id" 设置一个值可以使用一对多关系。
我知道您需要在填充多对多字段之前保存实例,因为它是一个单独的 table,但是我没有手动保存,而是依赖于 admin.py.我的应用程序中有一个单独的模型,它有一个多对多字段,通常保存在 admin.py 中,所以我不确定问题出在哪里
我的模型代码是:
class CaseFeature(models.Model):
"""Case-specific history features"""
case = models.ForeignKey(
Case,
on_delete=models.CASCADE,
related_name="features",
db_index=True)
feature_name = models.ForeignKey(
CoreFeature,
on_delete=models.PROTECT,
db_index=True)
response = models.TextField("Patient Response", max_length=500)
clerking_text = models.TextField(max_length=400)
tooltip = models.CharField(max_length=200, blank=True)
important = models.BooleanField()
answered_clarifying_qs = models.ManyToManyField(CoreClarifying, blank=True)
def clean(self):
# Make sure answered_clarifying are valid for this symptom
if self.answered_clarifying_qs not in self.feature_name.clarifying_qs:
raise ValidationError(_('Answered clarifying Qs do not match this symptom'))
def __str__(self):
return f"{self.case} - {self.feature_name}"
我的 admin.py 是:(当我注释掉它时没有任何变化我仍然得到一个值错误)
class CaseFeatureAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': forms.Textarea(attrs={'rows':5})}
}
...
admin.site.register(CaseFeature, CaseFeatureAdmin)
错误是由于保存前发生的清理方法造成的。解决方案是将干净的验证规则移至 ModelForm 而不是有效!
我正在尝试在 Django 中创建一个带有 manytomany 字段的模型,并使用默认的 admin.py 接口我收到一个 ValueError:需要在这么多之前为字段 "id" 设置一个值可以使用一对多关系。
我知道您需要在填充多对多字段之前保存实例,因为它是一个单独的 table,但是我没有手动保存,而是依赖于 admin.py.我的应用程序中有一个单独的模型,它有一个多对多字段,通常保存在 admin.py 中,所以我不确定问题出在哪里
我的模型代码是:
class CaseFeature(models.Model):
"""Case-specific history features"""
case = models.ForeignKey(
Case,
on_delete=models.CASCADE,
related_name="features",
db_index=True)
feature_name = models.ForeignKey(
CoreFeature,
on_delete=models.PROTECT,
db_index=True)
response = models.TextField("Patient Response", max_length=500)
clerking_text = models.TextField(max_length=400)
tooltip = models.CharField(max_length=200, blank=True)
important = models.BooleanField()
answered_clarifying_qs = models.ManyToManyField(CoreClarifying, blank=True)
def clean(self):
# Make sure answered_clarifying are valid for this symptom
if self.answered_clarifying_qs not in self.feature_name.clarifying_qs:
raise ValidationError(_('Answered clarifying Qs do not match this symptom'))
def __str__(self):
return f"{self.case} - {self.feature_name}"
我的 admin.py 是:(当我注释掉它时没有任何变化我仍然得到一个值错误)
class CaseFeatureAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': forms.Textarea(attrs={'rows':5})}
}
...
admin.site.register(CaseFeature, CaseFeatureAdmin)
错误是由于保存前发生的清理方法造成的。解决方案是将干净的验证规则移至 ModelForm 而不是有效!