问题
How can one serialize a model which has a foreign key to Django auth user so that a username can be retrieved? This is what I have tried through Tastypie:
def dehydrate(self, bundle):
posts = Post.objects.annotate(num_poster = Count('likedby')).order_by('-num_poster')
specificpost = posts.get(id__exact=bundle.data['id'])
likedList = specificpost.likedby.all()[:7]
liked_data = serializers.serialize('python', likedList, fields=('user__username', 'userPic'), use_natural_keys=True)
liked_actual = [d['fields'] for d in liked_data]
bundle.data['likepreview'] = liked_actual
return bundle
In the JSON that I get, I can see the userPic field but there is no username field, why is that?
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 17
},
"objects": [{
"id": "19",
"liked": 0,
"likepreview": [{
"userPic": "http://s3.amazonaws.com/post/mike/profile/photo/mikeProfilePic.jpg"
}
来源:https://stackoverflow.com/questions/15649522/serializing-a-model-which-has-a-foreign-key-to-django-auth-user