美文网首页
对于choice字段的显示第二个字段

对于choice字段的显示第二个字段

作者: lkning | 来源:发表于2018-04-08 14:07 被阅读0次
    # models.py
    class User(AbstractUser):
        GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )
    
        gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    
    
    # serializers.py 
    class UserSerializer(serializers.ModelSerializer):
        gender = serializers.CharField(source='get_gender_display')
    
        class Meta:
            model = User
    
    
    # viewsets.py
    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer
    

    两种显示第二个参数的方式

    class UserSerializer(serializers.ModelSerializer):
        gender = serializers.SerializerMethodField()
    
        class Meta:
            model = User
    
        def get_gender(self,obj):
            return obj.get_gender_display()
    

    或者

    gender = serializers.CharField(source='get_gender_display')
    

    相关文章

      网友评论

          本文标题:对于choice字段的显示第二个字段

          本文链接:https://www.haomeiwen.com/subject/fsgphftx.html