将相关资源与TastyPi相结合

2024-09-27 09:35:57 发布

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

如何在Tastype中组合多种资源?我有三个模型,我想结合:用户,个人资料和帖子。在

理想情况下,我希望配置文件嵌套在用户。我想从userpostsresource公开用户和所有配置文件位置。我不知道从这里到哪里去。在

class UserResource(ModelResource):

    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        fields = ['username','id','date_joined']

        #Improper Auth
        authorization = Authorization()

class UserProfileResource(ModelResource):

    class Meta:
        queryset = UserProfile.objects.all()
        resource_name = 'profile'


class UserPostResource(ModelResource):
    user = fields.ForeignKey(UserResource,'user', full=True)


    class Meta:
        queryset = UserPost.objects.all()
        resource_name = 'userpost'

        #Improper Auth
        authorization = Authorization()

以下是我的模型:

^{pr2}$

Tags: 用户name模型fieldsobjects配置文件allresource
1条回答
网友
1楼 · 发布于 2024-09-27 09:35:57

tastype字段(当资源是ModelResource时)允许传入attributekwarg,后者反过来接受常规的django嵌套查找语法。在

因此,首先这可能是有用的:

# in UserProfile model (adding related_name)
user = models.OneToOneField(User, related_name="profile")

鉴于上述变化,以下内容:

^{pr2}$

将在UserResource中公开来自UserProfile模型的数据。在

现在,如果您想在UserResource中公开一个位置列表(来自UserPost),您必须重写其中一个Tastypie方法。根据文档,一个好的候选方法是^{}方法。在

这样的方法应该有效:

# in UserPost model (adding related_name)
user = models.ForeignKey(User, related_name="posts")

class UserResource(ModelResource):
    # ....
    def dehydrate(self, bundle):
        posts = bundle.obj.posts.all()
        bundle.data['locations'] = [post.location for post in posts]
        return bundle
    # ...

相关问题 更多 >

    热门问题