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

标签 python django tastypie

如何在 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/

相关文章:

python - Visual Studio Code 的调试器和 pipenv

python - 如何在 MSYS2 上安装 Python 开发工具

Django : UnicodeDecodeError at/accounts/ProfileDetails/ 'utf8' codec can't decode byte 0xe1 in position 5915: invalid continuation byte

python - 如何配置 Tastypie 以将字段视为唯一字段?

javascript - 'infinite' 模式下的 Backbone.Paginator 在 model.destroy 上抛出 'Maximum call stack size exceeded'

python - Django Tastypie v0.11.1,POST请求,无法使用obj_create保存数据

python - 如何在多索引数据框中找到异常值帧

python - python中缺失值的标准异常是什么?

python - django-paypal 突然停止接收来自 Paypal 的信号

python - 看不到 Django 测试用例插入的记录