r.bhardwaj
r.bhardwaj

Reputation: 1613

Django Tastypie create API with complex calculation on database fields

I am new to Djnago/Tastypie and having trouble in creating an API with complex calculation. The model is as following :

class Customer(models.Model):
'''Customer details.'''
    name = models.CharField(max_length=200, null=True, blank=True)
    latitude = models.DecimalField(default=0, decimal_places=10,
                                  max_digits=15, blank=True, null=True)
    longitude = models.DecimalField(default=0, decimal_places=10,
                                   max_digits=15, blank=True, null=True)

Now the task is to create an API which will have latitude, longitude, radius as request parameters and we have to calculate all the Customers whose latitude and longitude falls within the given radius to the requested point.

Till now I have only experience of creating simple API using Tastypie. Can anybody please suggest me the possible resource class for this or any Django/Tastypie tutorial that might be helpful for creating this API ?
Thanks

Upvotes: 1

Views: 162

Answers (1)

PhoebeB
PhoebeB

Reputation: 8570

Two possible approaches both in a standard ModelResource

class MyResource(ModelResource):

  class Meta:
    queryset = MyModel.objects.all()
    ...

Do all the work of creating the object and add it to the bundle you return:

def obj_create(self, bundle, request=None, **kwargs):


    ref = bundle.data['ref']
    value = complex calculation here

    bundle.obj = MyModel.objects.create(ref=ref, value = value)


    return  bundle

Use the parent class to create the object and put it in the bundle and then amend the value:

def obj_create(self, bundle, request=None, **kwargs):


    bundle = super(MyResource, self).obj_create(
        bundle, request, user=request.user
    )
    bundle.obj.value = complex calculation here
    bundle.obj.save()


    return  bundle

Upvotes: 1

Related Questions