Serializing a model which has a foreign key to Django Auth User

╄→尐↘猪︶ㄣ 提交于 2019-12-11 05:42:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!