序列化具有Django Auth Us外键的模型

2024-10-03 17:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

如何序列化一个具有Django auth user外键的模型,以便可以检索用户名?这就是我尝试过的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字段,但是没有username字段,这是为什么?在

^{pr2}$

Tags: idfieldsdatausernamenumbundlepostsposter