Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms with get_or_create

Tags:

I am using Django ModelForms to create a form. I have my form set up and it is working ok.

form = MyForm(data=request.POST)  if form.is_valid():     form.save() 

What I now want though is for the form to check first to see if an identical record exists. If it does I want it to get the id of that object and if not I want it to insert it into the database and then give me the id of that object. Is this possible using something like:

form.get_or_create(data=request.POST) 

I know I could do

form = MyForm(instance=object) 

when creating the form but this would not work as I still want to have the case where there is no instance of an object

edit:

Say my model is

class Book(models.Model):     name = models.CharField(max_length=50)     author = models.CharField(max_length=50)     price = models.CharField(max_length=50) 

I want a form which someone can fill in to store books. However if there is already a book in the db which has the same name, author and price I obviously don't want this record adding again so just want to find out its id and not add it.

I know there is a function in Django; get_or_create which does this but is there something similar for forms? or would I have to do something like

if form.is_valid():      f = form.save(commit=false)     id = get_or_create(name=f.name, author=f.author, price=f.price) 

Thanks

like image 851
John Avatar asked Feb 19 '10 16:02

John


1 Answers

I like this approach:

if request.method == 'POST':     form = MyForm(request.POST)     if form.is_valid():        book, created = Book.objects.get_or_create(**form.cleaned_data) 

That way you get to take advantage of all the functionality of model forms (except .save()) and the get_or_create shortcut.

like image 91
rz. Avatar answered Sep 29 '22 01:09

rz.