Django Tastypie - 使用URL参数过滤ToManyField资源 [英] Django Tastypie - Filtering ToManyField resource with URL parameter

查看:288
本文介绍了Django Tastypie - 使用URL参数过滤ToManyField资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Tastypie为我的Django(v1.5)应用程序实现一个API。我想要能够过滤/限制父资源时获得的相关资源。

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()

我的资源: / p>

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,
        }

我想使用URL参数,可以使用 User 资源中的datetime过滤资源资源资源,例如: / p>

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 

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

获取用户的号码时区设备ID 数据列表过滤了给定的日期时间。

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?

感谢您的时间,我会感谢任何建议! p>

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

推荐答案

您可以将属性参数扩展到 data 字段具有全面的功能,并重新使用 DataResource

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 处理根据 DataResource 定义的过滤器。您只需要在 parent_id 上过滤。

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

参考

这篇关于Django Tastypie - 使用URL参数过滤ToManyField资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆