views:

53

answers:

1

I am looking for a good example of how to achieve the following:

I would like to use get_or_create to check whether an object already exists in my database. If it does not, then it will be created. If it does exist, then I will not create the new object, but need to raise a form error to inform the user that they need to enter different data (for example, a different username).

The view contains:

p, created = Person.objects.get_or_create(
   email = registration_form.cleaned_data['email'],
   defaults = {
       'creationDate': datetime.datetime.now(),                
       'dateOfBirth': datetime.date(1970,1,1)
})

So 'p' will contain the existing Person if it exists, or the new Person if not. I would like to act on the boolean value in 'created' in order to skip over saving the Person and re-display the registration_form and raise an appropriate form validation error.

The alternative I'm considering is doing a check in a custom Form validation method to see whether a Person exists with the data in the provided 'email' field, and just raising a validation error.

+3  A: 

This is not a good example usage of get_or_create. Form validation (which you obviously try to do) comes before saving and those shouldn't be mixed at all. You should be sure your form validated before saving, but the 'already exists' check is part of the validating.

In your form's clean() method, write something like this:

try:
    Person.objects.get(email=...)
    raise forms.ValidationError(...)
except Person.DoesNotExist:
    pass

This is the alternative you proposed and is the most sensible solution.

Good usage of get_or_create is for example a tagging library, where you want new tags to be created on the fly or information about old tags collected, without having to write try/except all the time.

Edit: also, if you wanted to do this to avoid the separated get/create cycle later on, make sure you use modelforms. The save method of modelforms returns you the just created instance.

KillianDS
Thanks for the tip about the ModelForms save() method. hard to find that out!
pfctdayelise