0

hi i try to add same value in a table many to many in django but i don't know how can i do it

this is my modles:

class Raza(models.Model):
     Nombre = models.CharField(max_length=50)
     Origen = models.CharField(max_length=45)
     Altura = models.CharField(max_length=10)
     Peso = models.CharField(max_length=10)
     Esperanza_vida = models.CharField(max_length=10)
     Actividad_fisica = models.CharField(max_length=45)
     Recomendaciones = models.CharField(max_length=500)
     Clasificacion_FCI = models.ForeignKey(Clasificacion_FCI,null=True,blank=True,on_delete=models.CASCADE)
     Tipo_pelo = models.ManyToManyField(Tipo_pelo,blank=True)
     Caracteristicas_fisicas = models.ManyToManyField(Caracteristicas_fisicas,blank=True)
     Caracter = models.ManyToManyField(Caracter,blank=True)
     Ideal = models.ManyToManyField(Ideal,blank=True)
     Tamanio = models.ForeignKey(Tamanio,null=True,blank=True,on_delete=models.CASCADE)
     User = models.ManyToManyField(User,blank=True)

and the User model are the default model that Django give me

i tried someone like that

class AgregarFav(views.APIView):
    def post(self, request, *args, **kwargs):
        idUsario= request.POST.get('isUsuario')
        idPerro = request.POST.get('idPerro')
        raza = Raza.User.add(idPerro,idUsario)
        raza.save()
        return HttpResponse(idUsario)

but i have the error 'ManyToManyDescriptor' object has no attribute 'add'

i want do something like that

table user 
id_usuario = 1
name = "Juan"

table raza
id_raza = 1 
name = "pitbull"

table user_raza
id_user_raza = 1
id_user = 1
id_raza = 1
JUAN ALVARES
  • 75
  • 11

3 Answers3

0

You shouldn't name fields of your model starting with uppercase letter because of PEP8.

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

Rename User to users (as your m2m connection means multiple instances on both sides), apply migrations and add instances of User to instance of Raza like this:

user = User.objects.get(id=usario_id)
Raza.objects.get(id=perro_id).users.add(user)

Django m2m add docs.

edit:

Actually you can add users not by instances but with pks. See this question.

Kyryl Havrylenko
  • 674
  • 4
  • 11
0

You edit the relation of a specific object, like:

Raza.objects.get(id=idPerro).User.add(idUsario)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

there are 2 ways of adding m2m relation.

1. Single attachment.

user = User.objects.get(id=usario_id)
r1 = Raza.objects.get(id=1)

user.razas.add(r1)

2. Bulk

user = User.objects.get(id=usario_id)
razas = []

p1 = Raza.objects.get(id=1)
p2 = Raza.objects.get(id=2)
razas.append(p1)
razas.append(p2)

user.razas.add(*razas)
Eddwin Paz
  • 2,842
  • 4
  • 28
  • 48