0

I am a newbie with Tastypie and it is wonderful the way you can achieve CRUD operations with it so quickly. But I would like to implement other kind of web services where the return value is other than a model. For example, if I had a simple model like this

class User(models.Model):
    name = models.CharField(max_length=20)
    age = models.PositiveSmallIntegerField()

and wanted to get the average age of all users via /api/v1/user/avg_age, how should I do it? Perhaps it is something related to Django URLs more than Tastypie but I am lost at this moment. So, the question is where/how should I define my custom REST web services? Thanks in advance

erbihanka
  • 185
  • 1
  • 10

1 Answers1

0

You can add the method to the model itself or put it in a service layer. After doing so you can easily add the value to the resource with a dehydration cycle.

Another option, which will allow filtering on the value, is to implement a model holding this data, e.g. a UserStatistics model. You can then add a foreign key relationship or create a stand-alone resource.

Because data won't likely change a whole lot and these calculations are more expensive I would encourage you to create a cronjob or task for such a model, only executing database writes periodically

Community
  • 1
  • 1
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100