6

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

1 回答 1

10

Tastypie 字段(当资源是 a 时ModelResource)允许传入attributekwarg,而 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' )
    # ...

UserProfileUserResource.

现在,如果您想在 中公开位置列表(来自UserPost),UserResource则必须覆盖其中一种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
    # ...
于 2012-09-15T09:22:03.473 回答