Search code examples
pythondjangotastypie

tastypie related resources group by


I'm new in TastyPie and I want some help with a maybe simple task (and in english language too D:). I have two related resources by a field. ForeignKey and I want get a result set that contains the total loops performed by the runners in a period of time. That requeriment is reflected in the next SQL query.

SELECT r.firstName, r.lastName, COUNT(l.id) FROM Runners r INNER JOIN Loops l ON r.id = l.runnerId WHERE l.start >= '1900-01-01' AND l.end <= '1900-01-02'

Resources.py

class LoopsResource(ModelResource):
    operators = fields.ForeignKey("OperatorsResource", "operators", full=True, null=True, blank=True)

class Meta:
    queryset = Loopssync.objects.all()
    resource_name = 'Loopssync'
    authorization = Authorization()
    #fields = []

    filtering = {
        "startedat" : ['gte', 'gt', 'lte', 'lt'],
        "finishedat" : ['gte', 'gt', 'lte', 'lt'],
        "operatorid": ALL_WITH_RELATIONS
    }

class RunnersResource(ModelResource):
    class Meta:
        queryset = Runners.objects.all()
        resource_name = 'Runners'
        authorization = Authorization()
        fields = ['id', 'firstname', 'lastname']
        filtering = {"id": ALL}

Models.py

class Loopssync(models.Model):
    remoteid = models.IntegerField(db_column='remoteId', blank=True, null=True)  
    startedat = models.DateTimeField(db_column='startedAt') 
    finishedat = models.DateTimeField(db_column='finishedAt')  
    runnerid = models.ForeignKey('Runners', db_column='runnerId')

class Runners(models.Model):
    firstname = models.TextField(db_column='firstName') 
    lastname = models.TextField(db_column='lastName')

Besides, I want to know what URI I should I use for obtain this set result in a browser.


Solution

  • Add after line 2:

    runners = fields.ToManyField("RunnersResource", "runners", full=True, null=True, blank=True)
    

    Then you should be able to do:

    ?startedat__gte=1900-01-01&finishedat__lte=1900-01-02
    

    There is no need to do count. You can simply count the amount of loops you get back. Or perhaps tastypie will even supply you with that information.