这是我的模特
class HighScore(models.Model):
user = models.OneToOneField(UserManagement, on_delete=models.CASCADE)
highScore = models.IntegerField(blank=True, null=True)
createDate = models.DateTimeField()
def __str__(self):
return "{}_HighScore".format(self.user)
这是我的观点:
def pullUserNames(request):
top_score = createHighScore()
top_users = (HighScore.objects.order_by('-highScore').filter(highScore__in=top_score[:10]))
top_users_serialized = serializers.serialize('json', top_users)
top_users_json = json.loads(top_users_serialized)
data = json.dumps(top_users_json)
return HttpResponse(data)
响应为:
[{"model": "scoremg.highscore", "pk": 2, "fields": {"user": 2, "highScore": 650, "createDate": "2018-12-25T20:34:51.826Z"}}, {"model": "scoremg.highscore", "pk": 1, "fields": {"user": 1, "highScore": 271, "createDate": "2018-12-17T21:48:34.406Z"}}]
在此响应{"user": 2, "highScore": 650, "createDate": "2018-12-25T20:34:51.826Z"}
中,highScore和createDate的脸很好,但是用户ID不是用户名,我如何编辑它以返回用户名?
我在上述视图的第二行之后测试了print(top_users),它打印-> user2_HighScore
user1_HighScore
谢谢
答案 0 :(得分:1)
使用DRF尝试此操作
serializer.py
:
class HighScoreSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(
slug_field='username'
)
class Meta:
model = HighScore
fields = '__all__'
答案 1 :(得分:0)
我认为,结合QuerySet的Annotation
和可序列化数据的自定义函数,您可以解决问题。
这是一个示例,您可以如何做:
import json
from django.db.models import F
def custom_serializer(a):
"""
Handy creation of the Queryset fields
And we exclude the fields that starts by '__'
which are Django internal references
This will lead to the representation of the annotated fields
that are generated by the QuerySert annotation
which are ignored by serializers.serialize() function
"""
return [{
'model': a.model.__name__, 'pk': k.pk, 'fields': {
i: j for i, j in k.__dict__.items() if not i.startswith('_')
}
} for k in a]
# Here we annotate a new field called username
# which holds the user's username using the F expression
top_users = HighScore.objects.order_by('highScore').filter(
highScore__in=top_score[:10]
).annotate(username=F('user__username'))
top_users_serialized = custom_serializer(top_users)
print(json.dumps(top_users_serialized))
您会得到这样的东西:
[{
"model": "scoremg.highscore",
"pk": 2,
"fields": {
"id": 2, # pk
"user_id": 2 # your user id
"username": "test", # your user's username
"highScore": 650,
"createDate": "2018-12-25T20:34:51.826Z"
}
},
...
]
编辑:
不使用自定义函数的更好方法,您可以使用queryset.values()
这样的方法:
top_users = HighScore.objects.order_by('highScore').filter(
highScore__in=top_score[:10]
).annotate(username=F('user__username'))
top_users_serialized = [elm for elm in top.users.values()]
print(json.dumps(top_users_serialized))
您会得到这样的东西:
[{
"id": 2, # pk
"user_id": 2 # your user id
"username": "test", # your user's username
"highScore": 650,
"createDate": "2018-12-25T20:34:51.826Z"
},
...
]
有关更多信息,请参阅: F() expression , QuerySet Annotation 和 QuerySet values < / p>
答案 2 :(得分:0)
在serializer.py文件的serializer类中,添加如下代码行:
user = serializers.SlugRelatedField(
read_only=True,
slug_field='username'
)
这将告诉您的序列化程序从 User 表中获取并返回用户名字段。