1

如果我有一个带有 django 字段和一些由 property() 函数调用的属性的 django 模型,tastepie 可以与这个虚拟字段交互吗?或者我必须在tastepie 的脱水、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 等于多少?

4

1 回答 1

1

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

method_field = fields.CharField(attribute='my_method')
于 2013-03-09T23:25:01.290 回答