I use a regular generic.edit.CreateView of Django to create an object according to user input. The MyModel has an UniqueConstrait so the creation would fail if the new object happens to match an existing one.
However, instead of telling users that creation fails due to duplicate records, I would like to simply return the existing object since this is what users want. I tried to override
def save(self, commit=True):
return MyModel.get_or_create(value=self.cleaned_data['value'])[0]
but this does not work because form._post_clean will call form.instance.full_clean with its default validate_constraints=True, so an error will return during form validation.
Essentially I am looking for a GetOrCreateView but I am not sure what is a clean way to achieve this (other than maybe overriding form._full_clean). Note that I am not looking for a UpdateView because we do not know in advance which existing object will be returned.
Edit: After struggling with the validation issue for a very long time, I finally abandoned CreateView and resorted to a simpler FormView. The FormView will simply get all the user input I need, before calling get_or_create(form.cleaned_data[...]) in form_valid(self, form).
.exist()? I think you can use it by doing:existing_object = MyModel.objects.get(id=pk).exist()then you can pass an error message.pkto get theexisting_object. The scenario is that the user is creating an object by entering a name in a form backed by aCreateView, the name happens to clash with an existing object so theCreateViewis supposed to return an existing object matching the user's input, instead of creating a new one.