当前位置:  开发笔记 > 编程语言 > 正文

django save()禁止防止由于未保存的相关对象而导致数据丢失

如何解决《djangosave()禁止防止由于未保存的相关对象而导致数据丢失》经验,为你挑选了1个好方法。

我正在尝试使用inlineformset创建一个父模型和一些子模型。以下是我的看法。该代码可用于将初始Rfq模型保存到数据库中,但是在尝试将行保存到inlineformset中时出错。这是一对多关系,但是使用ForeignKey字段完成。

# views.py
def rfq_create(request):
    form = RfqForm(request.POST or None)
    RfqFormSet = inlineformset_factory(Rfq, Rfqlines, form=RfqlinesForm, extra=5, can_delete=True)
    lines_formset = RfqFormSet(request.POST or None)
    title = "Create a new RFQ"
    context = {
        "title": title,
        "form": form,
        "lines_formset": lines_formset,
    }

    if form.is_valid() and lines_formset.is_valid():
        rfq = form.save(commit=False)
        rfq.user = request.user
        rfq.save()
        lines_formset.save()
        rfq_list = Rfq.objects.order_by('rfq_id')[:20]
        title = "RFQ List"
        context = {
            "title": title,
            "rfq_list": rfq_list
        }
        return render(request, "rfq.html", context)

    return render(request, "rfq_create.html", context)

我试过看官方的Django文档,但是它似乎并不适用...还是不是那么简单。

这是我的回溯

Environment:


Request Method: POST
Request URL: http://localhost:8000/rfq/create

Django Version: 1.8.7
Python Version: 3.4.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'django.forms.formsets',
 'jquery',
 'crispy_forms',
 'registration',
 'home',
 'rfq',
 'dashboard',
 'pipeline')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/brandon/employees/rfq/views.py" in rfq_create
  36.         lines_formset.save()
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/forms/models.py" in save
  636.         return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/forms/models.py" in save_new_objects
  767.             self.new_objects.append(self.save_new(form, commit=commit))
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/forms/models.py" in save_new
  900.             obj.save()
File "/home/brandon/employees/env/lib/python3.4/site-packages/django/db/models/base.py" in save
  685.                         "unsaved related object '%s'." % field.name

Exception Type: ValueError at /rfq/create
Exception Value: save() prohibited to prevent data loss due to unsaved related object 'rfq'.

Brandon C. B.. 6

问题的答案是这样的

lines_formset = RfqFormSet(request.POST or None, instance=form.instance)

form.instance是被忽略的关键。



1> Brandon C. B..:

问题的答案是这样的

lines_formset = RfqFormSet(request.POST or None, instance=form.instance)

form.instance是被忽略的关键。

推荐阅读
php
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有