Django Forms with get_or_create

前端 未结 5 960
清酒与你
清酒与你 2021-01-31 09:46

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


        
5条回答
  •  梦谈多话
    2021-01-31 10:23

    I would do this -

    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            name   = form.cleaned_data['name']
            author = form.cleaned_data['author']
            price  = form.cleaned_data['prince']
    
            if name and author and price:
                book, created = Book.objects.get_or_create(name=name, \
                  author=author, price=price)
    
                if created:
                    # fresh entry in db.
                else:
                    # already there, maybe update?
    
                book.save()
    

提交回复
热议问题