P
P
Pan Propan2021-07-30 13:23:13
Django
Pan Propan, 2021-07-30 13:23:13

How to make a ListField based on the model's CharField in the ModelSerializer?

I need the serializer to give me the scope field with an array of values ​​​​from the user_type field of my model.

models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
    USER_TYPE_CHOICES = (
      (1, 'customer'),
      (2, 'manufacturer'),
      (3, 'seller'),
    )
    name = models.CharField(max_length=50, null=True, blank=True)
    phone = models.CharField(max_length=12, verbose_name='Телефон')
    email = models.EmailField('Адрес электронной почты', unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()
    # Функция возвращает строковое описание поля ролм, для фронта
    def get_user_scope(self):
        if self.user_type == 1:
            scope = 'customer'
        elif self.user_type == 2:
            scope = 'manufacturer'
        elif self.user_type == 3:
            scope = 'seller'
        else:
            scope = ''
        return scope                        

    def __str__(self):
        return self.email

serializers.py
class UserSerializer(serializers.ModelSerializer):
    scope = serializers.ListField(child=serializers.CharField(source='get_user_scope'))
    
    def create(self, validated_data):
        return get_user_model().objects.create_user(**validated_data)
    
    class Meta:
        model = get_user_model()
        fields = ('email', 'password', 'phone', 'name', 'scope')
        extra_kwargs = {
            'password': {'write_only': True, 'min_length': 8},
        }


This code didn't work
class UserSerializer(serializers.ModelSerializer):
    scope = serializers.ListField(child=serializers.CharField(source='get_user_scope'))


I get the error
AssertionError: The `source` argument is not meaningful when applied to a `child=` field. Remove `source=` from the field declaration.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pan Propan, 2021-07-31
@mgis

In general, this is the arrangement.
Add the get_scope() method to the model

class CustomUser(AbstractBaseUser, PermissionsMixin):
    USER_TYPE_CHOICES = (
      (1, 'customer'),
      (2, 'manufacturer'),
      (3, 'seller'),
    )
    name = models.CharField(max_length=50, null=True, blank=True)
    phone = models.CharField(max_length=12, verbose_name='Телефон')
    email = models.EmailField('Адрес электронной почты', unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = CustomUserManager()
                      
    def get_scope(self):
      arr = []
      arr.append(self.get_user_type_display()) 
      return arr 
         
    def __str__(self):
        return self.email

Well, we edit the serializer itself
class UserSerializer(serializers.ModelSerializer):
    user_type = serializers.ListField(source='get_scope')
    # scope = serializers.CharField(source='get_user_type_display')
    
    def create(self, validated_data):
        return get_user_model().objects.create_user(**validated_data)
    
    class Meta:
        model = get_user_model()
        fields = ('email', 'password', 'phone', 'name', 'user_type')
        extra_kwargs = {
            'password': {'write_only': True, 'min_length': 8},
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question