django将自我从queryset中排除以进行验证 [英] django exclude self from queryset for validation

查看:142
本文介绍了django将自我从queryset中排除以进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我自己的清洁方法来查看某些其他表格是否已经有一个具有相同字符串的字段。
只要我创建一个,这一切都很好,但是当我尝试编辑它时,它会发现本身并返回错误。
现在我想知道如何使用我的干净方法排除实例本身

  def clean_name(self):
raw_data = self.cleaned_data ['name']
data = raw_data.title()

如果Country.objects.filter(name = data).exists():
raise forms.ValidationError((has has a country with a name:%s)%data)
if Province.objects.filter(name = data).exists():
raise forms.ValidationError((已经有一个省名称为%s)%data)
如果Region.objects.filter(name = data).exists():
raise forms.ValidationError ((已经有一个名称为%s的地区)%data)
返回数据


$ b $我知道有一个.exclude(),但需要一个变量与它一起传递,不知道我如何可以得到它与我的干净的方法

解决方案

假设您的 clean_name 方法在ModelForm上, n访问相关联的模型实例 self.instance 。第二,一个简单的方法来判断一个模型实例是新创建还是已经存在于数据库中,是检查其主键的值。如果主键是 None ,则该模型是新创建的。



所以,验证逻辑可能看起来像这个:

  def clean_name(self):
name = self.cleaned_data ['name']。
qs = Country.objects.filter(name = name)
如果self.instance.pk不是无:
qs = qs.exclude(pk = self.instance.pk)
如果qs.exists():
raise forms.ValidationError(已经有一个名称为s的国家/地区%name)

为了清楚起见,我只显示一个查询集。我可能会创建一个包含所有三个查询的元组,然后迭代它们。添加exclude子句的代码和对 exists()的调用都可以在循环中处理,因此只需要写入一次(DRY)。 p>

I am working with my own clean method to see if some other table already had a field with the same string. This all goes fine as long as i am creating one, but when i try to edit it, it find "itself" and gives back the error. Now am i wondering how can i exclude the instance itself in my clean method

def clean_name(self):
    raw_data = self.cleaned_data['name']
    data = raw_data.title()

    if Country.objects.filter(name=data).exists():
        raise forms.ValidationError(("There is already a country with the name: %s") % data)
    if Province.objects.filter(name=data).exists():
        raise forms.ValidationError(("There is already a province with the name: %s") % data)
    if Region.objects.filter(name=data).exists():
        raise forms.ValidationError(("There is already a region with the name: %s") % data) 
    return data

i know there is a .exclude() but that needs a variable to be passed along with it, not sure how i could get that along with my clean method

解决方案

Assuming your clean_name method is on a ModelForm, you can access the associated model instance at self.instance. Second, a simple way to tell if a model instance is newly created, or already existing in the database, is to check the value of its primary key. If the primary key is None, the model is newly created.

So, your validation logic could look something like this:

def clean_name(self):
    name = self.cleaned_data['name'].title()
    qs = Country.objects.filter(name=name)
    if self.instance.pk is not None:
        qs = qs.exclude(pk=self.instance.pk)
    if qs.exists():
        raise forms.ValidationError("There is already a country with name: %s" % name)

I've only shown one query set for clarity. I'd probably create a tuple containing all three querysets, and iterate over them. The code for adding the exclude clause, and the call to exists() could all be handled inside the loop, and therefore only needs to be written once (DRY).

这篇关于django将自我从queryset中排除以进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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