TastyPie和属性

时间:2012-12-30 23:06:53

标签: django django-models tastypie

如果我有一个带有django字段的django模型和一些由property()函数调用的属性,那么tastypie可以与这个虚拟字段进行交互吗?或者我必须将逻辑包含在tastypie的脱水,obj_create,obj_update函数中?

型号:

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

如果它可能很短,那么如果我通过tasypie传递x = 1,y = 2那么x会相等吗?

1 个答案:

答案 0 :(得分:0)

如果您希望资源上的字段来自方法,您可以包含以下内容:

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