2012-12-30 58 views
0

如果我有一個django模型和django字段以及property()函數調用的某些屬性,那麼tastypie可以與這個虛擬字段進行交互嗎?或者我必須將邏輯包含到tastypie的脫水,obj_create,obj_update函數中?TastyPie和屬性

型號:

class A (models.Model): 
    x = models.CharField() 
    def get_y(self): 
     return self.x 
    def set_y(self, value): 
     self.y = value 
    y = property(get_y, set_y) 

資源可短:

class AResource(ModelResource): 
    class Meta: 
     queryset = A.objects.all() 
     fields = ['id','x','y'] 

還是應只要:

class AResource(ModelResource): 
    class Meta: 
     queryset = A.objects.all() 
     fields = ['id','x','y'] 

def dehydrate(self, bundle): 
    bundle.data['y'] = bundle.obj.x 
    return bundle 


def obj_create(self, bundle, request=None, **kwargs): 
    bundle.obj.y = bundle.data['y'] 
    bundle = super(AResource, self).obj_create(
     bundle, 
     request, 
    ) 

    return bundle 

def obj_update(self, bundle, request=None, **kwargs): 
    bundle = super(AResource, self).obj_update(
     bundle, 
     request, 
    ) 
    bundle.obj.y = bundle.data['y'] 
    return bundle 

如果它可能是短,然後會是什麼如果我通過x = 1,y = 2通過tasypie,x等於?

回答

0

如果您想對來自方法的資源領域,可以包括這樣的事情:

method_field = fields.CharField(attribute='my_method') 
+0

是它複製? http://stackoverflow.com/questions/9078035/how-to-expose-a-property-virtual-field-on-a-django-model-as-a-field-in-a-tasty –