gpt4 book ai didi

python - Django 1.8.3 - 使用相关对象进行模型字段验证

转载 作者:太空狗 更新时间:2023-10-30 00:17:06 32 4
gpt4 key购买 nike

对于以下模型集(Foo、Bar),您可以施加交叉验证规则,如以下代码片段的 Bar.clean 中的规则,直到 django 1.7。

同一代码段在 django 1.8.3 中引发了 RelatedObjectDoesNotExist 错误。

在 django 1.8.3 中实现相同结果的新方法和改进方法是什么?

(我包含了 admin.py 代码只是为了展示如何使用这些模型。)

模型.py

from django.db import models
from django.core.exceptions import ValidationError

class Foo(models.Model):
name = models.CharField("Name", blank=True, max_length=300)

class Bar(models.Model):
name = models.CharField("Name", blank=True, max_length=300)
foo = models.ForeignKey('Foo', verbose_name='Foo')

def clean(self):
if self.name + self.foo.name != 'FooBar':
raise ValidationError('Concatenation should be FooBar.')

管理员.py

from django.contrib import admin
import models

class BarInline(admin.TabularInline):
model = models.Bar

class FooAdmin(admin.ModelAdmin):
model = models.Foo
inlines = [BarInline,]

site = admin.site
site.register(models.Foo,FooAdmin)

最佳答案

我已经对您的代码添加了一个简单的输出修改

def clean(self):
print(self.__dict__)

if self.name + self.foo.name != 'FooBar':
raise ValidationError('Concatenation should be FooBar.')

简单的打印语句将在执行主代码之前打印出 Bar 对象。

现在我已经用 Django 1.8.x 测试了代码,我得到了你提到的异常结果:

{'_state': <django.db.models.base.ModelState object at 0x7ff55cd30710>, 'id': None, 'foo_id': None, 'name': 'Bar 1'}

现在又用Django 1.7.x测试了一遍,运行正常,输出结果为:

{'_foo_cache': <Foo: Foo object>, 'name': 'Bar 1', 'id': None, 'foo_id': None, '_state': <django.db.models.base.ModelState object at 0x7f731151c9e8>}

正如您可能注意到 None 中的两种情况下的 foo_id 但神奇的是 _foo_cache 在 Django 1.8 中被删除的东西

我可以建议您的替代方法是将您的验证移动到表单中

进行了以下更改:管理员.py

class BarInline(admin.TabularInline):
model = Bar
form = BarForm

表单.py

class BarForm(forms.models.ModelForm):
class Meta:
model = Bar
fields = ('name',)

def clean(self):
data = self.cleaned_data
if not data['name'] + data['foo'].name == "foobar":
raise ValidationError('Concatenation should be FooBar.')

关于python - Django 1.8.3 - 使用相关对象进行模型字段验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31371746/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com