Direct assignment to the forward side of a Many-to-Many set is prohibited. Use morador.set() Instead

Asked

Viewed 205 times

1

I’m building an API for a condo system, and when I try to select the residents, I get the following exception:

TypeError at /apartamento/
Direct assignment to the forward side of a many-to-many set is prohibited. Use morador.set() instead

As the exception itself suggests, I tried to use the set to save the residents, however, only the last selected resident is saved. I also tried using add and the same happens.

Model

class Apartamento(models.Model):
    numero = models.CharField(max_length=10, null=False, blank=False)
    condominio = models.ForeignKey(Condominio, on_delete=models.CASCADE)
    morador = models.ManyToManyField(Usuario, related_name='moradia')

    class Meta:
        db_table = 'apartamento'
        verbose_name = 'Apartamento'
        verbose_name_plural = 'Apartamentos'

    def __str__(self):
        return self.numero

View

class ApartamentoView(viewsets.ModelViewSet):
    queryset = Apartamento.objects.all()
    serializer_class = ApartamentoSerializer

    def create(self, request):
        condominio = Condominio.objects.get(id=request.data['condominio'])
        morador = Usuario.objects.get(id=request.data['morador'])
        Apartamento.objects.create(numero=request.data['numero'], condominio=condominio, morador=morador)

        headers = self.get_success_headers(request.data)

        return Response(
            {'Message' : 'Apartamento cadastrado com sucesso!'},
            status=status.HTTP_201_CREATED,
            headers=headers
        )
  • when you try to register only one works and when you try to register several does not work? what is the multiplicity of Apartamento with Condominio?

  • Yes, if I register only one resident works, if I register more than one it only saves the last one. 1 condominium for n apartments

  • in which case I think you should wear a for to iterate between residents and manage to add them

  • ah don’t forget that when we have a field with many-to-many you must use add or set see the doc

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.