1

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?

Павел Тявин
  • 2,349
  • 4
  • 21
  • 31

1 Answers1

1

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

method_field = fields.CharField(attribute='my_method')
Pat B
  • 514
  • 1
  • 5
  • 14
  • Is it duplicated? http://stackoverflow.com/questions/9078035/how-to-expose-a-property-virtual-field-on-a-django-model-as-a-field-in-a-tasty – Tony Sep 13 '14 at 09:32