Django - Direct assignment to the forward side of a many-to-many set is prohibited










1















I have this class in my project:



class ManejoEventoSanitario(models.Model):
id_evento_sanitario = models.AutoField(primary_key=True)
id_tipo_evento = models.ForeignKey(TipoEvento, on_delete=models.PROTECT)
descricao = models.CharField(max_length=90, blank=True, null=True)
dt_evento_sanitario = models.DateField(blank=True, null=True)
dt_prox_evento = models.DateField(blank=True, null=True)
responsavel = models.ForeignKey(Pessoa, on_delete=models.PROTECT)
animais = models.ManyToManyField(Animal)
produtos = models.ManyToManyField(DoseProduto)

objects = models.Manager()


And I have this post endpoint in my ._views :



class ApiEventoSanitarioAnimal(APIView):
def post(self, request, format=None):
data_evento = request.POST['data_evento']
tipo_evento = request.POST['tipo_evento']
responsavel = request.POST['responsavel']
descricao = request.POST['descricao']
data_proximo_evento = request.POST['data_proximo_evento']
animais_json = jsonpickle.decode(request.POST['animais'])
produtos_json = jsonpickle.decode(request.POST['produtos'])

tipo_evento = get_object_or_404(TipoEvento, id_tipo_evento=tipo_evento)
responsavel = get_object_or_404(Pessoa, id_pessoa=responsavel)

animais = set()
for animal_json_id in animais_json:
animal = get_object_or_404(Animal, id_animal=animal_json_id)
animais.add(animal)

dose_quantidade_produtos = set()
for produto_json in produtos_json:
produto = get_object_or_404(Produto, id_produto=produto_json['id'])
unidade_medida = Unidade.objects.filter(descricao=produto_json['unidade']).first()
dose_quantidade = produto_json['dose']

dose_produto = DoseProduto()
dose_produto.id_produto = produto
dose_produto.id_unidade_medida = unidade_medida
dose_produto.quantidade = dose_quantidade
dose_produto.save()
dose_quantidade_produtos.add(dose_produto)

m_evento_sanitario = ManejoEventoSanitario()
m_evento_sanitario.dt_evento_sanitario = data_evento
m_evento_sanitario.id_tipo_evento = tipo_evento
m_evento_sanitario.responsavel = responsavel
m_evento_sanitario.descricao = descricao
m_evento_sanitario.save()

#Adiciono os animais e produtos ao evento sanitario cadastro
m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()

return Response(status=status.HTTP_200_OK)


What I'm trying to do is:



  • Create a ManejoEventoSanitario (this is an event in Real life)

  • Put the animals that will be in this event

  • Put the products that will be used in this event

But when the code arrives in this part:



m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()


It throws this error:



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


I tried as a list too but it doesn't work. The animais and dose_quantidades_produtos already are a set.



Please, what am I doing wrong?










share|improve this question






















  • Possible duplicate of How to add data into ManyToMany field?

    – Johan
    Nov 14 '18 at 13:18















1















I have this class in my project:



class ManejoEventoSanitario(models.Model):
id_evento_sanitario = models.AutoField(primary_key=True)
id_tipo_evento = models.ForeignKey(TipoEvento, on_delete=models.PROTECT)
descricao = models.CharField(max_length=90, blank=True, null=True)
dt_evento_sanitario = models.DateField(blank=True, null=True)
dt_prox_evento = models.DateField(blank=True, null=True)
responsavel = models.ForeignKey(Pessoa, on_delete=models.PROTECT)
animais = models.ManyToManyField(Animal)
produtos = models.ManyToManyField(DoseProduto)

objects = models.Manager()


And I have this post endpoint in my ._views :



class ApiEventoSanitarioAnimal(APIView):
def post(self, request, format=None):
data_evento = request.POST['data_evento']
tipo_evento = request.POST['tipo_evento']
responsavel = request.POST['responsavel']
descricao = request.POST['descricao']
data_proximo_evento = request.POST['data_proximo_evento']
animais_json = jsonpickle.decode(request.POST['animais'])
produtos_json = jsonpickle.decode(request.POST['produtos'])

tipo_evento = get_object_or_404(TipoEvento, id_tipo_evento=tipo_evento)
responsavel = get_object_or_404(Pessoa, id_pessoa=responsavel)

animais = set()
for animal_json_id in animais_json:
animal = get_object_or_404(Animal, id_animal=animal_json_id)
animais.add(animal)

dose_quantidade_produtos = set()
for produto_json in produtos_json:
produto = get_object_or_404(Produto, id_produto=produto_json['id'])
unidade_medida = Unidade.objects.filter(descricao=produto_json['unidade']).first()
dose_quantidade = produto_json['dose']

dose_produto = DoseProduto()
dose_produto.id_produto = produto
dose_produto.id_unidade_medida = unidade_medida
dose_produto.quantidade = dose_quantidade
dose_produto.save()
dose_quantidade_produtos.add(dose_produto)

m_evento_sanitario = ManejoEventoSanitario()
m_evento_sanitario.dt_evento_sanitario = data_evento
m_evento_sanitario.id_tipo_evento = tipo_evento
m_evento_sanitario.responsavel = responsavel
m_evento_sanitario.descricao = descricao
m_evento_sanitario.save()

#Adiciono os animais e produtos ao evento sanitario cadastro
m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()

return Response(status=status.HTTP_200_OK)


What I'm trying to do is:



  • Create a ManejoEventoSanitario (this is an event in Real life)

  • Put the animals that will be in this event

  • Put the products that will be used in this event

But when the code arrives in this part:



m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()


It throws this error:



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


I tried as a list too but it doesn't work. The animais and dose_quantidades_produtos already are a set.



Please, what am I doing wrong?










share|improve this question






















  • Possible duplicate of How to add data into ManyToMany field?

    – Johan
    Nov 14 '18 at 13:18













1












1








1








I have this class in my project:



class ManejoEventoSanitario(models.Model):
id_evento_sanitario = models.AutoField(primary_key=True)
id_tipo_evento = models.ForeignKey(TipoEvento, on_delete=models.PROTECT)
descricao = models.CharField(max_length=90, blank=True, null=True)
dt_evento_sanitario = models.DateField(blank=True, null=True)
dt_prox_evento = models.DateField(blank=True, null=True)
responsavel = models.ForeignKey(Pessoa, on_delete=models.PROTECT)
animais = models.ManyToManyField(Animal)
produtos = models.ManyToManyField(DoseProduto)

objects = models.Manager()


And I have this post endpoint in my ._views :



class ApiEventoSanitarioAnimal(APIView):
def post(self, request, format=None):
data_evento = request.POST['data_evento']
tipo_evento = request.POST['tipo_evento']
responsavel = request.POST['responsavel']
descricao = request.POST['descricao']
data_proximo_evento = request.POST['data_proximo_evento']
animais_json = jsonpickle.decode(request.POST['animais'])
produtos_json = jsonpickle.decode(request.POST['produtos'])

tipo_evento = get_object_or_404(TipoEvento, id_tipo_evento=tipo_evento)
responsavel = get_object_or_404(Pessoa, id_pessoa=responsavel)

animais = set()
for animal_json_id in animais_json:
animal = get_object_or_404(Animal, id_animal=animal_json_id)
animais.add(animal)

dose_quantidade_produtos = set()
for produto_json in produtos_json:
produto = get_object_or_404(Produto, id_produto=produto_json['id'])
unidade_medida = Unidade.objects.filter(descricao=produto_json['unidade']).first()
dose_quantidade = produto_json['dose']

dose_produto = DoseProduto()
dose_produto.id_produto = produto
dose_produto.id_unidade_medida = unidade_medida
dose_produto.quantidade = dose_quantidade
dose_produto.save()
dose_quantidade_produtos.add(dose_produto)

m_evento_sanitario = ManejoEventoSanitario()
m_evento_sanitario.dt_evento_sanitario = data_evento
m_evento_sanitario.id_tipo_evento = tipo_evento
m_evento_sanitario.responsavel = responsavel
m_evento_sanitario.descricao = descricao
m_evento_sanitario.save()

#Adiciono os animais e produtos ao evento sanitario cadastro
m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()

return Response(status=status.HTTP_200_OK)


What I'm trying to do is:



  • Create a ManejoEventoSanitario (this is an event in Real life)

  • Put the animals that will be in this event

  • Put the products that will be used in this event

But when the code arrives in this part:



m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()


It throws this error:



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


I tried as a list too but it doesn't work. The animais and dose_quantidades_produtos already are a set.



Please, what am I doing wrong?










share|improve this question














I have this class in my project:



class ManejoEventoSanitario(models.Model):
id_evento_sanitario = models.AutoField(primary_key=True)
id_tipo_evento = models.ForeignKey(TipoEvento, on_delete=models.PROTECT)
descricao = models.CharField(max_length=90, blank=True, null=True)
dt_evento_sanitario = models.DateField(blank=True, null=True)
dt_prox_evento = models.DateField(blank=True, null=True)
responsavel = models.ForeignKey(Pessoa, on_delete=models.PROTECT)
animais = models.ManyToManyField(Animal)
produtos = models.ManyToManyField(DoseProduto)

objects = models.Manager()


And I have this post endpoint in my ._views :



class ApiEventoSanitarioAnimal(APIView):
def post(self, request, format=None):
data_evento = request.POST['data_evento']
tipo_evento = request.POST['tipo_evento']
responsavel = request.POST['responsavel']
descricao = request.POST['descricao']
data_proximo_evento = request.POST['data_proximo_evento']
animais_json = jsonpickle.decode(request.POST['animais'])
produtos_json = jsonpickle.decode(request.POST['produtos'])

tipo_evento = get_object_or_404(TipoEvento, id_tipo_evento=tipo_evento)
responsavel = get_object_or_404(Pessoa, id_pessoa=responsavel)

animais = set()
for animal_json_id in animais_json:
animal = get_object_or_404(Animal, id_animal=animal_json_id)
animais.add(animal)

dose_quantidade_produtos = set()
for produto_json in produtos_json:
produto = get_object_or_404(Produto, id_produto=produto_json['id'])
unidade_medida = Unidade.objects.filter(descricao=produto_json['unidade']).first()
dose_quantidade = produto_json['dose']

dose_produto = DoseProduto()
dose_produto.id_produto = produto
dose_produto.id_unidade_medida = unidade_medida
dose_produto.quantidade = dose_quantidade
dose_produto.save()
dose_quantidade_produtos.add(dose_produto)

m_evento_sanitario = ManejoEventoSanitario()
m_evento_sanitario.dt_evento_sanitario = data_evento
m_evento_sanitario.id_tipo_evento = tipo_evento
m_evento_sanitario.responsavel = responsavel
m_evento_sanitario.descricao = descricao
m_evento_sanitario.save()

#Adiciono os animais e produtos ao evento sanitario cadastro
m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()

return Response(status=status.HTTP_200_OK)


What I'm trying to do is:



  • Create a ManejoEventoSanitario (this is an event in Real life)

  • Put the animals that will be in this event

  • Put the products that will be used in this event

But when the code arrives in this part:



m_evento_sanitario.animais = animais
m_evento_sanitario.produtos = dose_quantidade_produtos
m_evento_sanitario.save()


It throws this error:



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


I tried as a list too but it doesn't work. The animais and dose_quantidades_produtos already are a set.



Please, what am I doing wrong?







python django






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 13:14









WitnessTruthWitnessTruth

178111




178111












  • Possible duplicate of How to add data into ManyToMany field?

    – Johan
    Nov 14 '18 at 13:18

















  • Possible duplicate of How to add data into ManyToMany field?

    – Johan
    Nov 14 '18 at 13:18
















Possible duplicate of How to add data into ManyToMany field?

– Johan
Nov 14 '18 at 13:18





Possible duplicate of How to add data into ManyToMany field?

– Johan
Nov 14 '18 at 13:18












1 Answer
1






active

oldest

votes


















2














There's no reason to put those into a set. Move the creation of m_evento_sanitario before those loops, then for each one instead of adding it to a set add it directly to the m2m:



for animal_json_id in animais_json:
animal = get_object_or_404(Animal, id_animal=animal_json_id)
m_evento_sanitario.animais.add(animal)


and similarly for produtos.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301096%2fdjango-direct-assignment-to-the-forward-side-of-a-many-to-many-set-is-prohibit%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    There's no reason to put those into a set. Move the creation of m_evento_sanitario before those loops, then for each one instead of adding it to a set add it directly to the m2m:



    for animal_json_id in animais_json:
    animal = get_object_or_404(Animal, id_animal=animal_json_id)
    m_evento_sanitario.animais.add(animal)


    and similarly for produtos.






    share|improve this answer



























      2














      There's no reason to put those into a set. Move the creation of m_evento_sanitario before those loops, then for each one instead of adding it to a set add it directly to the m2m:



      for animal_json_id in animais_json:
      animal = get_object_or_404(Animal, id_animal=animal_json_id)
      m_evento_sanitario.animais.add(animal)


      and similarly for produtos.






      share|improve this answer

























        2












        2








        2







        There's no reason to put those into a set. Move the creation of m_evento_sanitario before those loops, then for each one instead of adding it to a set add it directly to the m2m:



        for animal_json_id in animais_json:
        animal = get_object_or_404(Animal, id_animal=animal_json_id)
        m_evento_sanitario.animais.add(animal)


        and similarly for produtos.






        share|improve this answer













        There's no reason to put those into a set. Move the creation of m_evento_sanitario before those loops, then for each one instead of adding it to a set add it directly to the m2m:



        for animal_json_id in animais_json:
        animal = get_object_or_404(Animal, id_animal=animal_json_id)
        m_evento_sanitario.animais.add(animal)


        and similarly for produtos.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 14:55









        Daniel RosemanDaniel Roseman

        449k41581636




        449k41581636



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301096%2fdjango-direct-assignment-to-the-forward-side-of-a-many-to-many-set-is-prohibit%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            ReactJS Fetched API data displays live - need Data displayed static

            政党