django - 通过中间类保存 ManyToMany

标签 django django-models django-views

我阅读了很多关于这个问题的链接:

How to save a django model with a manyToMany Through relationship, AND regular manyToMany relationships

How to save a django model with a manyToMany Through relationship, AND regular manyToMany relationships

django manytomany through

包括文档: https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

但无法通过中介类保存我的 M2M。

我的模型:

class Promotor(PessoaFisica):
    user = models.OneToOneField(User, blank=True, null=True)    


class Setor(models.Model):
    nome = models.CharField(max_length=255)
    promotores = models.ManyToManyField(Promotor, through='Membro', blank=True, null=True)     

    class Meta:
        verbose_name_plural = 'setores'

    def __unicode__(self):
        return "%s" % (self.nome)

class Membro(models.Model):
    promotor = models.ForeignKey(Promotor)
    setor = models.ForeignKey(Setor)
    data_inclusao = models.DateField(auto_now=True)  

保存方法:

def add_setor(request):
    form = SetorForm(request.POST or None)
    if form.is_valid():
        s = form.save()    
        setor = get_object_or_404(Setor, pk = s.id)    
        for promotor_id in request.POST.getlist('promotores'):
            membro = Membro.objects.create(promotor_id=promotor_id, setor_id=setor.id)          
            membro.save()         
        messages.add_message(request, messages.SUCCESS, 'Setor cadastrado com sucesso!')
        return HttpResponseRedirect('/project/setor/index/')
    return render_to_response('project/setor/form.html', locals(), context_instance=RequestContext(request))

错误是:

Cannot set values on a ManyToManyField which specifies an intermediary model.  Use setor.Membro's Manager instead.

如果 save() 方法提交“false”,则“setor”没有“id”放入 Membro 对象。 如何通过中间类保存setor? 谢谢!

最佳答案

您的表单中有 promotores 字段链接到模型,因此 save() 尝试将其保存到 m2m 字段。您可以使用 commit=False 保存表单,然后手动保存对象(它不会触及 m2m),然后像现在一样保存 m2m。

附:我猜你应该使用 form.cleaned_data['promotores'] 而不是 request.POST。天知道客户端实际发布了什么。

关于django - 通过中间类保存 ManyToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238433/

相关文章:

python - DjangoForeignKey self 条件

django - 确保 Django 中记录上的 2 个选择字段不相等

python - 我如何继承 Django CreateView

python - type str 没有定义 __round__ 方法/如何获取表单字段? django 和cropper.js?

django - 使用 django admin 创建整个 Web 应用程序

python - 从rest_framework.serializer.Field中的django.db.models.Field继承help_text

django - 具有继承模型的 ModelForm 的表单字段

python - (Django) 通过更新 UserProfile,图像无法正确保存

python - django admin static 服务于错误的 url

django - Typeform 安全 API 和 Django : Not Verifiying Hash Correctly