Home > Enterprise >  DRF Many to many creat user error: type object 'name_object' has no attribute 'bulk_c
DRF Many to many creat user error: type object 'name_object' has no attribute 'bulk_c

Time:11-09

I'm creating an api that will register users related to a customer and also to an organizational group, but I'm having problems registering the user's group.

whenever I try to register I get the following error:

type object 'GrupoOrganizacional' has no attribute 'bulk_create'

the error happens, but when I check the database and the user is registered, however, without organizational group.

Could you help me understand what I'm doing wrong?

my models.py

class Cliente(models.Model):
    nome = models.CharField(max_length=100, unique=True, null=True)
    documento = models.CharField(max_length=30, blank=True, default='00.000.000/0001-00')
    logo = models.CharField(max_length=255, blank=True, null=True)
    data_de_criacao = models.DateField(default=date.today)
    cliente_ativo = models.BooleanField(default=True)
    background_img = models.CharField(max_length=255, blank=True, null=True)
    cor_primaria = models.CharField(max_length=10, blank=True, null=True)
    cor_secundaria = models.CharField(max_length=10, blank=True, null=True)


    def __str__(self):
        return self.nome

class GrupoOrganizacional(models.Model):
    id_grupo = models.BigAutoField(primary_key=True, unique=True) 
    nome_grupo = models.CharField(max_length=100, blank=False, null=False)
    cliente = models.ForeignKey(Cliente, blank=True, null=True ,on_delete=models.CASCADE)

    def __str__(self):
        return self.nome_grupo
    
class Usuario(AbstractUser):
   
    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    cliente = models.ForeignKey(Cliente, blank=True, null=True ,on_delete=models.CASCADE)
    first_name = models.CharField(max_length=100, blank=False, null=False)
    last_name = models.CharField(max_length=100, blank=False, null=False)
    username = models.CharField(max_length=50, blank=True, null=True)
    email = models.EmailField(max_length=100, blank=False, null=False, unique=True, error_messages={'unique': "O email cadastrado já existe."})
    password = models.CharField(max_length=100, blank=False, null=False)
    usuario_ativo = models.BooleanField(default=True)
    grupo = models.ManyToManyField(GrupoOrganizacional, related_name='grupos')
    
    is_staff = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)

    def __str__(self):
        return "%s (%s)" %(self.first_name, self.cliente)

my views.py

class GruposViewSet(viewsets.ModelViewSet):
    ''' Lista todos os grupos cadastrados '''
    queryset = GrupoOrganizacional.objects.all()
    serializer_class = ListaGruposSerializer

    permission_classes = [IsAuthenticated, IsAdminUser]
    
class UsuariosViewSet(viewsets.ModelViewSet):
    ''' Lista todos os usuarios cadastrados'''
    queryset = Usuario.objects.all()
    serializer_class = UsuarioSerializer

    permission_classes = [IsAuthenticated, IsAdminUser]
    

my serializers.py

class GruposDoUsuarioSerializer(PrimaryKeyRelatedField ,serializers.ModelSerializer):
    '''Serializer para listar todos os grupos organizacionais cadastrados'''
    #grupo_id = serializers.PrimaryKeyRelatedField( many=True, read_only=True )

    class Meta:
        model = GrupoOrganizacional
        fields = ['id_grupo']


class UsuarioSerializer(serializers.ModelSerializer):
    '''Serializer para listar, criar e atualizar os usuarios'''
    
    grupo = GruposDoUsuarioSerializer(many=True, queryset=GrupoOrganizacional.objects.all()) 

    password = serializers.CharField(
        style={'input_type': 'password'},
        write_only=True,
        label="Senha"
    )

    password_confirm = serializers.CharField(
        style={'input_type': 'password'},
        write_only=True,
        label="Confirme a senha"
    )

    is_staff = serializers.BooleanField(
        label="Membro da Equipe",
        help_text="Indica que usuário consegue acessar o site de administração."
    )

    is_superuser = serializers.BooleanField(
        label="SuperUsuário",
        help_text="Indica que este usuário tem todas as permissões sem atribuí-las explicitamente."
    )

    class Meta:
        model = Usuario
        fields = ('id','cliente', 'first_name', 'last_name', 'username', 'email', 
        'password', 'password_confirm', 'usuario_ativo', 'grupo', 'is_staff', 'is_superuser')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        '''Permite caradastrar e atualizar contas'''
        grupo_data = validated_data.pop('grupo')
        password = self.validated_data.get('password')
        password_confirm = self.validated_data.get('password_confirm')
        if password != password_confirm:
            raise serializers.ValidationError({'password': 'As senhas não são iguais.'})
        validated_data.pop('password_confirm')

        usuario = Usuario.objects.create(**validated_data)

        grupo_organizacional_list = []
        for grupo_data in grupo_data:
            grupo_organizacional_list.append(GrupoOrganizacional(grupo_data)) 
            
            # failed attempts 
            # grupo_organizacional_list.append(GrupoOrganizacional(**grupo_data)) # error ModelBase object argument after ** must be a mapping, not GrupoOrganizacional
            # grupo_organizacional_list.append(GrupoOrganizacional(**grupo_data['id_grupo'])) # error ModelBase object argument after ** must be a mapping, not GrupoOrganizacional
            # grupo_organizacional_list.append(Usuario(**grupo_data)) # error ModelBase object argument after ** must be a mapping, not GrupoOrganizacional
            # grupo_organizacional_list.append(**grupo_data['id_grupo']) # error GrupoOrganizacional' object is not subscriptable

        grupo_organizacional_list = GrupoOrganizacional.bulk_create(grupo_organizacional_list) # error type object 'GrupoOrganizacional' has no attribute 'bulk_create'

        # failed attempts
        # grupo_organizacional_list = GrupoOrganizacional.objects.create(grupo_organizacional_list) # error: create() takes 1 positional argument but 2 were given

        usuario.grupo.set(*grupo_organizacional_list)
        usuario.set_password(password)

        usuario.save()
        
        return usuario

I left some of the attempts in the code itself, my traceback tells me the following:

Internal Server Error: /usuarios/
Traceback (most recent call last):
  File "/home/my-pc/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/my-pc/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/my-pc/.local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/mixins.py", line 24, in perform_create
    serializer.save()
  File "/home/my-pc/.local/lib/python3.8/site-packages/rest_framework/serializers.py", line 212, in save
    self.instance = self.create(validated_data)
  File "/home/my-pc/sistema-web-beanalytic/be-api/clientes/serializers.py", line 89, in create
    grupo_organizacional_list = GrupoOrganizacional.bulk_create(grupo_organizacional_list) 
AttributeError: type object 'GrupoOrganizacional' has no attribute 'bulk_create'

EDIT: I'm trying to register an existing group (previously registered) to a new user

CodePudding user response:

Use objects, it should:

GrupoOrganizacional.objects.bulk_create(grupo_organizacional_list)

https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-create

  • Related