1

我有一些美味的资源,我正在脱水,所以我可以在结果中返回资源的蛞蝓(名称),但我在重新补水时遇到了麻烦。

我尝试设置,例如, bundle.data['profile'] = { 'name': bundle.data['profile'] }但我无法让它工作,它看起来好像需要所有数据才能构建对象,而不仅仅是一些字段

在这个例子中,hydrate_profile工作,但它取决于bundle.obj.profile已经加载。我不确定我是否总是可以假设。

在 的情况下dehydrate_roles,我不知道应该返回什么,返回模型列表或 QuerySet 不起作用,看起来正确的做法(在这两种方法中)是返回正确的资源 uri,在这两种情况下,但我不知道如何在没有太多硬编码的情况下构建它:我需要从字段(或至少从 Resource 类)中检索原始模型类,以获取对象,在为了得到它的PK然后构建uri ..对我来说听起来太牵强了。

所以:我该怎么办?我的hydrate_profile实施是正确的,还是会咬我的屁股?我应该返回hydrate_roles什么?

class MinionResource(ModelResource):
    """
    Resource for :models:`inventory.minions.models.Minion`
    """
    roles = fields.ToManyField(RoleResource, 'roles')
    profile = fields.ForeignKey(clouds_api.CloudProfileResource, 'profile')

    class Meta:
        queryset = models.Minion.objects.all()
        resource_name = 'minion/minion'
        filtering = {
            'id': ALL,
            'name': ALL,
            'roles': ALL_WITH_RELATIONS,
            'profile': ALL_WITH_RELATIONS,
        }

    def dehydrate_profile(self, bundle):
        return bundle.obj.profile.name
    def hydrate_profile(self, bundle):
        bundle.data['profile'] = bundle.obj.profile
        return bundle

    def dehydrate_roles(self, bundle):
        return list(bundle.obj.roles.all().values_list('name', flat=True))
4

1 回答 1

2

I can't exactly answer what is right, but as far as I know, on Profile part, you will get problem when you create new object that doesn't have profile linked yet.

However, what I regularly do is to only define if I want information or not.

class MinionResource(ModelResource):
    roles = fields.ToManyField(RoleResource, 'roles', full=True)
    profile = fields.ForeignKey(clouds_api.CloudProfileResource, 'profile', full=True)

This should be enough already. However, if you don't like to be this way, you can do this.

class MinionResource(ModelResource):
    roles = fields.ListField()
    profile = fields.ForeignKey(clouds_api.CloudProfileResource, 'profile', full=True)

    def dehydrate_roles(self, bundle):
        return map(str, bundle.obj.roles.all())
于 2013-09-06T01:06:26.957 回答