djangotastypie

Tastypie resource filtering through foreign keys


I have some Django (3.1) models connected through foreign keys

class Drone(models.Model):
    serial = models.CharField(max_length=200, null=False, unique=True)

class Dive(models.Model):
    measurement_time = models.DateTimeField(db_index=True)
    drone = models.ForeignKey(
        Drone,
        on_delete=models.PROTECT,
        null=True,
    )

class Density(models.Model):
    measurement_time = models.DateTimeField(db_index=True)
    depth = models.IntegerField()
    density = models.FloatField(null=True)
    dive = models.ForeignKey(
        Dive,
        on_delete=models.PROTECT,
        db_index=True,
        null=True,
    )

I have a Tastypie (0.14.3) ModelResource class for my API defined like

class DensityResource(ModelResource):
    class Meta:
        queryset = Density.objects.filter(dive__drone_id=13).order_by('-measurement_time', 'depth')

that works as I'd expect for the single dive__drone_id. I want to implement get parameter filtering so I can do something like /?order_by=-measurement_time&order_by=depth&dive__drone_id=13 so I rewrote this class to

class DensityResource(ModelResource):
    class Meta:
        queryset = Density.objects.all()
        filtering = {
            'dive__drone_id': ALL
        }
        ordering = ['measurement_time', 'depth']

and the ordering works fine but not the filtering. What am I missing here?


Solution

  • I found a solution modifying the build_filters method instead:

    class DensityResource(ModelResource):
        class Meta:
            queryset = Density.objects.all()
            ordering = ['measurement_time', 'depth']
    
        def build_filters(self, filters=None, **kwargs):
            orm_filters = super(DensityResource, self).build_filters(filters, **kwargs)
            if 'dive__drone_id' in filters.keys():
                orm_filters['dive__drone_id'] = filters['dive__drone_id']
            return orm_filters