我有一个简单的视图,“运动员”应该只显示一个名称和id,以及一些额外的相关数据。但是我从记录中取回整个数据集。
@api_view(['GET'])
@permission_classes((permissions.AllowAny,))
def get_by_years(request):
athletes = AthleteProfile.objects.filter(owner=request.user)
athletes_json = NotesAthleteSerializer(athletes, many=True)
return Response(athletes_json.data)
我期待这种格式:
[
{
"id": 215,
"first_name": "Joseph",
"last_name": "Doe",
"graduation_year": 2016,
"notes": "fdgdfg wew",
}
]
相反,它提供了所有细节,如:
[
{
"id": 215,
"first_name": "Joseph",
"last_name": "Doe",
"graduation_year": 2016,
"notes": "fdgdfg wew",
"email": "joedoe@gmail.com",
"date_of_birth": null,
"mobile_number": "123-234-23271",
"team_name": "Wildcats",
"coach_name": "",
"coach_email": "",
"coach_number": "",
"event_seen": "NA",
"jersey_number": 1,
"rank": 2,
"public_record": false,
"notify_key": "f9781efee667d26cdeb6cead447e49bdd8a836a3",
"notified_on": "2016-11-02T10:58:37.131000Z",
"level_of_interest": "1",
"user": null,
"owner": 30,
"sport_position": null,
"next_step": null,
"next_steps": [
1,
2
]
}
]
以下是我的序列化设置:
class NotesAthleteSerializer(serializers.ModelSerializer):
class Meta:
model = AthleteProfile
field = ('id', 'first_name', 'last_name', 'graduation_year', 'notes')
我是否错误地初始化了“NotesAthleteSerializer”?
我尝试了其他几种定义序列化的方法,例如:
class NotesAthleteSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(read_only=True)
last_name = serializers.CharField(read_only=True)
graduation_year = serializers.IntegerField(read_only=True)
notes = serializers.CharField(read_only=True)
class Meta:
model = AthleteProfile
read_only_fields = ('id', 'first_name', 'last_name', 'graduation_year', 'notes')
和
class NotesAthleteSerializer(serializers.ModelSerializer):
class Meta:
model = AthleteProfile
read_only_fields = ('id', 'first_name', 'last_name', 'graduation_year', 'notes')
和
class NotesAthleteSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(read_only=True)
last_name = serializers.CharField(read_only=True)
graduation_year = serializers.IntegerField(read_only=True)
notes = serializers.CharField(read_only=True)
class Meta:
model = AthleteProfile
field = ('id', 'first_name', 'last_name', 'graduation_year', 'notes')
read_only_fields = ('id', 'first_name', 'last_name', 'graduation_year', 'notes')
答案 0 :(得分:0)
我是一个完全白痴,我有" field"而不是"字段" ....
class NotesAthleteSerializer(serializers.ModelSerializer):
class Meta:
model = AthleteProfile
field = ('id', 'first_name', 'last_name', 'graduation_year', 'notes')
相反,它必须是:
class NotesAthleteSerializer(serializers.ModelSerializer):
class Meta:
model = AthleteProfile
fields = ('id', 'first_name', 'last_name', 'graduation_year', 'notes')