I read a lot of references to this problem:
How to save a django model with manyToMany Through relation and manyToMany regular relationships
How to save a django model with manyToMany Through relation and manyToMany regular relationships
django manytomany through
Enable DOC:
https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
But I can not save my M2M with an intermediate class.
My models:
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)
Save method:
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))
Error:
Cannot set values on a ManyToManyField which specifies an intermediary model. Use setor.Membro Manager instead.
If the save () method commits "false", "setor" does not have an "id" to place the Membro object. How to save setor using this through a mediation class? Thank!
source
share