Django Tastypie - Filtering ToManyField resource with URL parameter

不问归期 提交于 2019-12-18 18:38:55

问题


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, e.g.:

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!


回答1:


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.



来源:https://stackoverflow.com/questions/20035462/django-tastypie-filtering-tomanyfield-resource-with-url-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!