Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

django exclude self from queryset for validation

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...