使用多种格式在Django中保存ManytoMany字段

时间:2019-10-31 20:11:20

标签: python django

我正在尝试以3种形式进行以下处理,这些形式会立即处理: 1.保存电子邮件的主题行(有效) 2.保存电子邮件内容。 (这有效) 3.保存电子邮件标题(有效),并将关系保存到主题行和电子邮件内容(无效)。

我已经阅读了我所有与错误有关的页面。我已经尝试了各种不同的方法,但是它们都没有为我工作。

View.py:


def email_subject_create_view(request):
    if request.method == 'POST':
        email_subject_form = EmailSubjectForm(request.POST)
        email_content_form = EmailContentForm(request.POST)
        email_form = EmailForm(request.POST)
        if email_subject_form.is_valid() and email_content_form.is_valid() and email_form.is_valid() :
            subject = email_subject_form.save(commit=False)
            subject.time_created = datetime.datetime.now()
            contractor = Contractor.objects.get(user_id=request.user.id)
            subject.save()
            email_subject_form.save_m2m()

            content = email_content_form.save(commit=False)
            content.time_created = datetime.datetime.now()
            content.save()
            email_content_form.save_m2m()

            email = email_form.save(commit=False)
            email.time_created = datetime.datetime.now()

            # this is what I want to do. email.email_core_contents is a M2M field
            email.email_subject_lines = subject.id


            email.save()

context = {
        'email_subject_form': EmailSubjectForm(),
        'email_content_form': EmailContentForm(),
        'email_form': EmailForm(),
}
return render(request, 'advertise/email_subject_create.html', context)

我尝试过:

email.email_subject_lines = EmailSubject.objects.get(pk=subject.id)
email.email_subject_lines.set(subject)
email.email_subject_lines.set(pk=subject.id)

我也尝试了不使用代码的.save_m2m()部分的情况。

编辑:

主要示例中的错误:

Direct assignment to the forward side of a many-to-many set is prohibited. Use email_subject_lines.set() instead.

3组中的1组出现错误:

Direct assignment to the forward side of a many-to-many set is prohibited. Use email_subject_lines.set() instead.

3组中的2组错误:

"<Email: sfeaesfe>" needs to have a value for field "id" before this many-to-many relationship can be used.

3组中的3组中的错误:

"<Email: graegre>" needs to have a value for field "id" before this many-to-many relationship can be used.

1 个答案:

答案 0 :(得分:0)

找到了两个解决方案。在这里,以防将来有人遇到相同的问题。

1:使用添加方法。

email.email_subject_lines.add(subject)
email.email_core_contents.add(content)

2。再次从数据库中获取两个对象(Email和EmailSubject)。

email2 = Email.objects.get(id=email.id)
subject2 = EmailSubject.objects.filter(id=subject.id)
email2.email_subject_lines.set(subject2)
email2.save()

不确定为什么它可以使用第二种方法,而不是原来的方法。请注意,我必须在第二个表达式中使用filter而不是get