我有这样的models.py
GENDER =(
('MALE',1),
('FEMALE',2),
('OTHERS',3)
)
class User(BaseModel, AbstractUser):
type = models.IntegerField(choices=USER_TYPE,null=True)
gender = models.IntegerField(choices=GENDER,null=True)
列出学生的Views.py就是这样
def list(self,request):
for adm in StudentAdmission.objects.all():
user = adm.student.user
tmp['user'] = UserGetSerializer(user).data
ud = UserDetail.objects.filter(user_id=user.id)
if ud:
tmp['user_detail'] = UserDetailSerializer(ud.first()).data
像这样的serializer.py ...
class UserBaseSerializer(serializers.Serializer):
first_name = serializers.CharField(max_length=120,required=True)
last_name = serializers.CharField(max_length=120,required=True)
email = serializers.EmailField(required=True)
class UserSerializer(UserBaseSerializer):
gender = serializers.IntegerField()
type = serializers.IntegerField(default=3)
class UserGetSerializer(UserBaseSerializer):
gender = serializers.SerializerMethodField()
type = serializers.IntegerField(default=3)
def get_gender(self, obj):
#Here Confusion
return {'id':obj.gender, 'value':value}
它以性别返回输出1,而不是返回男性。我要返回男性,而不是1。为此,我做了一个get_gender()函数从元组中查找并返回该对象ID的值。 所以我的问题是我该如何编写get_gender()函数来查找Gender元组。
对不起英语,希望您能理解我的问题
答案 0 :(得分:2)
使用模型的get_FOO_display
方法:
def get_gender(self, obj):
return obj.get_gender_display()
或仅指定是字段的来源:
class UserGetSerializer(UserBaseSerializer):
gender = serializers.CharField(source='get_gender_display')
请注意,您的GENDER
元组的值有误。应该像这样(actual_value, human_readable)
:
GENDER =(
(1, 'MALE'),
(2, 'FEMALE'),
(3, 'OTHERS')
)