Model form save. Get the saved object

匆匆过客 提交于 2019-12-30 01:36:10

问题


If I have a model form and save it like:

f = FormModel(request.POST)
if f.is_valid():
    f.save()

How can I get back that object that has just been saved?


回答1:


When you save a modelform, it returns the saved instance of the model. So all you have to do is assign it to a variable:

f = MyModelForm(request.POST)
if f.is_valid():
    m = f.save()

You do not need to mess around with commit=False or any of that stuff unless you are handling more complex data.




回答2:


If you know that the model is saved (so that a proper instance exists) you can also do:

model = form.instance



回答3:


Ah I just found this!

    # Create a form instance with POST data.
>>> f = AuthorForm(request.POST)

# Create, but don't save the new author instance.
>>> new_author = f.save(commit=False)

# Modify the author in some way.
>>> new_author.some_field = 'some_value'

# Save the new instance.
>>> new_author.save()

# Now, save the many-to-many data for the form.
>>> f.save_m2m()


来源:https://stackoverflow.com/questions/7428245/model-form-save-get-the-saved-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!