如何为Django管理员创建复杂的Django模型验证? [英] How can I create sophisticated Django Model Validation for Django Admin?

查看:141
本文介绍了如何为Django管理员创建复杂的Django模型验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有以下模型:

  class Bout(models.Model):
fighter_1 = models ForeignKey(Fighter,related_name =bout_fighter_1)
fighter_2 = models.ForeignKey(Fighter,related_name =bout_fighter_2)
winner = models.ForeignKey(Fighter,related_name =bout_winner,
blank = True,null = True,help_text ='留空为绘图')
date = models.DateField()
cancelled = models.BooleanField()

我想对其记录的笨蛋管理。偶然地,我想创建三个规则:


  1. 战斗机1与战斗机2不同(这只适用于monty python skit)。


  2. 获胜者应该在比赛中(即战斗机1或战斗机2)


  3. 在比赛发生之前无法设定获胜者。 (毕竟这不是WWE。)


所有这三个规则都需要检查一个字段与另一个字段在同一条记录中。是否可以在django中使用本机django方法或使用python?

解决方案

简单的答案:你可以实现这在Django中使用native django方法。我不知道你的意思是本机Django方法;我假设你的意思是调用Django API。



有几种方法可以解决这个问题。如果您的用户只能使用您提供的表单创建 Bout 实例,则表单的验证方法可以测试您提到的条件。例如:

  class BoutForm(forms.ModelForm):
class Meta:
model = Bout

def clean(self):
fighter_1 = self.cleaned_data.get('fighter_1')
fighter_2 = self.cleaned_data.get('fighter_2')
获胜者= self.cleaned_data.get('winner')
date = self.cleaned_data.get('date')

如果没有(fighter_1和fighter_2和(fighter_1.id!= fighter_2) )
raise forms.ValidationError(两个战士都不一样)

如果没有(获胜者和(winner.id == fighter_1.id或winner.id == fighter_2) id))
raise forms.ValidationError(Winner is not in the fight)

如果没有(日期和日期< datetime.today()):
raise form.ValidationError(获胜者不在战斗)

返回self.cleaned_data

上述代码片段不完整。您可以调整它以满足您的需求。还要看看Django的新悬念的表单验证器



如果另一方面您的用户可以使用API​​创建实例(例如,通过实例化 Bout 类他们的程序),那么你必须通过覆盖 Bout 类的 save()方法来进行验证。


I have the following model in Django:

class Bout (models.Model):
    fighter_1 = models.ForeignKey(Fighter, related_name="bout_fighter_1")
    fighter_2 = models.ForeignKey(Fighter, related_name="bout_fighter_2")
    winner = models.ForeignKey(Fighter, related_name="bout_winner", 
        blank=True, null=True, help_text='Leave blank for draw.') 
    date = models.DateField()
    cancelled = models.BooleanField()

I would like to "idiot-proof" the administration for its records. Incidently, I want to create three rules:

  1. Fighter 1 is not the same as fighter 2 (which is only good for a monty python skit).

  2. Winner should be in the bout (i.e., either Fighter 1 or Fighter 2)

  3. The winner can't be set before the match takes place. (After all, this isn't WWE.)

All three of these rules require checking one field against another field in the same record. Is it possible to do this in django, either using native django methods or resorting to python?

解决方案

Short answer: you can achieve this in Django using "native django methods". I am not sure what exactly you mean by "native Django methods"; I am assuming that you mean making calls to the Django API.

There are a couple of ways to go about this. If your users can only create Bout instances using a form that you provide then the form's validation methods can test for the conditions you mentioned. For e.g.:

class BoutForm(forms.ModelForm):
    class Meta:
        model = Bout

    def clean(self):
        fighter_1 = self.cleaned_data.get('fighter_1')
        fighter_2 = self.cleaned_data.get('fighter_2')
        winner = self.cleaned_data.get('winner')  
        date = self.cleaned_data.get('date')

        if not (fighter_1 and fighter_2 and (fighter_1.id != fighter_2)):
            raise forms.ValidationError("Both fighters cannot be the same")

        if not (winner and (winner.id == fighter_1.id or winner.id == fighter_2.id)):
            raise forms.ValidationError("Winner is not in the fight")

        if not (date and date < datetime.today()):
            raise forms.ValidationError("Winner is not in the fight")

        return self.cleaned_data

The above snippet is incomplete. You can tweak it to meet your needs. Also take a look at Django's new fangled form validators.

If on the other hand your users can create instances using the API (say, by instantiating the Bout class in their programs) then you'll have to do the validation by overriding the save() method of the Bout class.

这篇关于如何为Django管理员创建复杂的Django模型验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆