序列化它有一个外键的Django Auth用户模型(Serializing a model whic

2019-10-17 21:52发布

一个人怎么可以序列具有外键的Django auth用户,这样用户名可以检索一个模型? 这是我经历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

在JSON,我得到的,我可以看到userPic领域,但没有用户名场,这是为什么?

 {
"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"
    }
文章来源: Serializing a model which has a foreign key to Django Auth User