gpt4 book ai didi

python - 将相关资源与 TastyPie 相结合

转载 作者:太空狗 更新时间:2023-10-29 22:19:50 28 4
gpt4 key购买 nike

如何在 TastyPie 中组合多个资源?我有 3 个模型要合并:用户、个人资料和帖子。

理想情况下,我希望配置文件嵌套在用户中。我想从 UserPostResource 公开用户和所有个人资料位置。我不确定从这里到哪里去。

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()

这是我的模型:

class UserProfile(models.Model):

user = models.OneToOneField(User)

website = models.CharField(max_length=50)
description = models.CharField(max_length=255)
full_name = models.CharField(max_length=50)


class UserPost(models.Model):
user = models.ForeignKey(User)

datetime = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=255, blank=True)
location = models.CharField(max_length=255, blank= True)

最佳答案

Tastypie 字段(当资源是 ModelResource 时)允许传入 attribute kwarg,后者又接受常规的 django 嵌套查找语法。

所以,首先这可能是有用的:

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

鉴于上述更改,以下内容:

from tastypie import fields

class UserResource(ModelResource):
# ...
website = fields.CharField(attribute = 'profile__website' )
description = fields.CharField(attribute = 'profile__description' )
full_name = fields.CharField(attribute = 'profile__full_name' )
# ...

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

现在,如果您想在 UserResource 中公开位置列表(来自 UserPost),您将必须覆盖 Tastypie 方法。根据文档,一个好的候选者是 dehydrate()。方法。

像这样的东西应该可以工作:

# 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
# ...

关于python - 将相关资源与 TastyPie 相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12435992/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com