如何在Django drf中获得数组格式的响应? 我是python-drf编程的新手。请提供解决方案的帮助。
我只希望team_users为数组格式,但是现在它以数组形式返回,每个字母都用引号引起来。
{ "id": 3, "team_name": "team 3", "team_icon": "/media/icon/underground_3Dz5sfD.png", "team_users": [ "[", "'", "s", "k", "a", "r", "a", "n", "7", "1", "4", "@", "g", "m", "a", "i", "l", ".", "c", "o", "m", "'", ",", " ", "'", "s", "a", "m", "p", "l", "e", "1", "2", "3", "@", "g", "m", "a", "i", "l", ".", "c", "o", "m", "'", "]" ] },
所需格式为:
"id": 3, "team_name": "team 3", "team_icon": "/media/icon/underground_3Dz5sfD.png", "team_users": ["first_email", "second_email"]
这是serializers.py中的代码
class TeamSerializer(serializers.ModelSerializer):
team_users = serializers.ListField(child=serializers.EmailField(min_length=0, max_length=100))
class Meta():
model=Team
fields = ('id','team_name', 'team_icon', 'team_users')
models.py
class Team(models.Model):
team_name = models.CharField(max_length=255)
team_icon = models.ImageField()
team_users = models.EmailField()
在views.py
class GetTeam(APIView):
def get(self, request, *args, **kwargs):
data_list = []
teams = models.Team.objects.all()
for team in teams:
data_list.append(serializers.TeamSerializer(team).data)
return Response(data_list)
答案 0 :(得分:1)
一种可能的解决方案是使用'SerializerMethodField'
class TeamSerializer(serializers.ModelSerializer):
team_users = serializers.SerializerMethodField(read_only=True)
def get_team_users(self, obj):
return [x.email for x in obj.team_users]
还取决于您的团队用户模型,但是您可以根据自己的需要进行调整。
答案 1 :(得分:1)
class GetTeam(APIView):
def get(self, request, *args, **kwargs):
teams = models.Team.objects.all()
return Response(serializers.TeamSerializer(team, many=True).data)