2013-08-27 25 views
1

我有一些Tastypie資源,我正在脫水,所以我可以返回結果中的資源'slugs(名稱),但我無法重新補充它們。如何在Tastypie中水合ToOneField和ToManyField

我試過設置,例如,bundle.data['profile'] = { 'name': bundle.data['profile'] }但我無法得到那個工作,它看起來好像它需要的所有數據,以建立對象,而不僅僅是某些領域

在這個例子中, hydrate_profile的作品,但它取決於bundle.obj.profile已被加載。我不確定我總能假設這一點。

dehydrate_roles的情況下,我不知道應該返回什麼,返回一個模型列表或者一個QuerySet不起作用,它看起來像(兩個方法中)要做的正確的事情是返回在這兩種情況下都是正確的資源URI,但我不知道如何在沒有太多硬編碼的情況下構建它:我需要從字段(或至少從Resource類)檢索原始Model類,以便獲取對象,以獲得它的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)) 

回答

2

我不能確切回答什麼是正確的,但據我所知,在檔案的一部分,你會當你創建一個沒有個人資料鏈接然而新的對象獲取的問題。

但是,我經常做的只是定義我是否需要信息。

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

這應該已經夠了。但是,如果你不喜歡這樣,你可以做到這一點。

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