【问题标题】:Combine Related Resources With TastyPie将相关资源与 TastyPie 相结合
【发布时间】:2012-09-15 09:01:16
【问题描述】:

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

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

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

    【讨论】:

    • UserProfile 与 User 相关,UserPost 与 User 相关,您能提供一个例子吗?
    • 如果您可以粘贴您的模型并通过UserResource 说出您想公开哪个模型的哪些属性,那么可以。
    • 很棒的kgr,感谢您的出色回答。这真的帮助我更多地了解 Tastypie。
    • 太棒了!我很高兴我能帮上忙 :) 作为旁注,我可以告诉你,Tastypie 可以做很多事情,我推荐它(例如它比活塞好得多),所以找出它的古怪之处是一个值得投资的时间。跨度>
    • 这是否仅在模型中对应的 ForeignKey 字段中也存在 related_name 时才有效? (并且具有相同的价值?)这将非常值得一提。
    猜你喜欢
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2012-07-30
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多