简体   繁体   中英

Django Tastypie - Filtering ToManyField resource with URL parameter

I am working on implementing an API for my Django (v1.5) application using Tastypie. I would like to be able to filter/limit the related resources I get when the parent resource.

Here are my (simplified) models:

# myapp/models.py
class User(models.Model):
    number = models.IntegerField()
    device_id = models.CharField(verbose_name="Device ID", max_length=255)
    timezone = models.CharField(max_length=255, blank=True)

    def data(self, limit=0):
        result = Data.objects.filter(patient_id = self.id).order_by('-datetime').values('datetime', 'value')
        if limit != 0:
            result = result[:limit]
        return result

class Data(models.Model):
    user = models.ForeignKey(User)
    datetime = models.DateTimeField()
    value = models.IntegerField()

My resources:

# api/resources.py
class DataResource(ModelResource):
    class Meta:
        queryset = Data.objects.all()
        resource_name = 'cgm'
        fields = ['value', 'datetime']
        serializer = Serializer(formats=['json', 'xml'])
        filtering = {
            'datetime': ('gte', 'lte'),
        }
        include_resource_uri = False

    def dehydrate(self, bundle):
        bundle.data['timestamp'] = calendar.timegm(bundle.data['datetime'].utctimetuple())
        return bundle


class UserResource(ModelResource):

    data = fields.ToManyField(DataResource, attribute=lambda bundle: Data.objects.filter(patient_id=bundle.obj.id), full=True, related_name='data', null=True)

    class Meta:
        queryset = User.objects.all().order_by('number')
        resource_name = 'user'
        fields = ['number', 'timezone', 'device_id'],
        serializer = Serializer(formats=['json', 'xml'])
        filtering = {
            'data': ALL_WITH_RELATIONS,
        }

I would like to be able to filter the Data resources by 'datetime' inside the User resource using an URL parameter, eg:

127.0.0.1:8000/api/v1/user/1/?format=json&datetime__gte=2013-11-14%2012:00:00 

or

127.0.0.1:8000/api/v1/user/1/?format=json&data__datetime__gte=2013-11-14%2012:00:00

to get the User's number , timezone , device id and Data list filtered with the given datetime .

I don't want to have to query the Data resources separately to filter them, I want the whole thing bundled within the User resource. Is there a way to implement a filter applied to the nested resource using the framework?

Thanks for your time, I'll appreciate any suggestion!

You can extend your attribute argument you've passed to the data field with a full-scale function and reuse the DataResource :

def filter_data_items(bundle):
    res = DataResource()
    new_bundle = Bundle(request=bundle.request)
    objs = res.obj_get_list(new_bundle)
    return objs.filter(parent_id=bundle.obj.pk)

res.obj_get_list handles building and applying filters as defined per your DataResource . You just need to filter it futher on parent_id .

Reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM