django exclude self from queryset for validation

后端 未结 1 1411
失恋的感觉
失恋的感觉 2020-12-18 02:05

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

相关标签:
1条回答
  • 2020-12-18 02:29

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

    0 讨论(0)
提交回复
热议问题