Павел Тявин
Павел Тявин

Reputation: 2649

TastyPie and properties

If I have a django model with django fields and some properties called by property() function, can tastypie interact with this virtual fields? Or I have to include logic into tastypie's dehydrate, obj_create, obj_update function?

Model:

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)

Can resources be as short as:

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

Or should it be as long as:

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

If it could be short then what would be x equal if I pass x = 1, y = 2 by tasypie?

Upvotes: 1

Views: 906

Answers (1)

Pat B
Pat B

Reputation: 564

If you want fields on a resource that come from methods, you can include something like this:

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

Upvotes: 1

Related Questions