带有get_or_create的Django表单 [英] Django Forms with get_or_create

查看:303
本文介绍了带有get_or_create的Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django ModelForms创建一个表单。我有我的表单设置,它工作正常。

  form = MyForm(data = request.POST)

如果form.is_valid():
form.save()

我现在想要的是为了首先检查表单看是否存在相同的记录。如果我想要它获取该对象的id,如果不是,我希望它将其插入数据库,然后给我该对象的id。可以使用以下方法:

  form.get_or_create(data = request.POST)

我知道我可以做

  = MyForm(instance = object)

在创建表单时,但这不会工作,因为我仍然想有没有对象的实例



编辑:



说我的模型是

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

我想要一个可以填写书籍的表格。但是,如果db中已经有一本书有相同的名称,作者和价格,我显然不希望这个记录再次添加,所以只想找出它的id,而不是添加它。



我知道Django中有一个函数; get_or_create这样做,但是有什么类似的表单?或者我需要做一些像

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

谢谢

解决方案

我喜欢这种方法:



如果request.method =='POST':
form = MyForm(request.POST)
如果form.is_valid():
书,则$ $ $ $ $ ,created = Book.objects.get_or_create(** form.cleaned_data)

这样你就可以模型表单(.save()除外)和get_or_create快捷方式的所有功能的优点。


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

解决方案

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.

这篇关于带有get_or_create的Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆