0

我正在使用sweetpie API开发一个 Django 应用程序,我基本上想创建对象,然后按日期过滤它们,以便我知道哪些对象是新的(“给我从那个日期到今天的所有对象”之类的)。我不知道这是否重要(我认为确实如此),但我正在使用 mongoDB。

我挣扎的地方是当我尝试做 ?&published__gte=2013-02-01 简单的事情时,按日期过滤最合乎逻辑的方法是什么?我希望我有任何意义,如果不是毫不犹豫地问我精度。

这是我的模型:

class Object(models.Model):

    name = models.CharField(max_length=200)
    published = models.DateTimeField('date published')

这是我的资源:

class ObjectResource(ModelResource):

    class Meta:
        queryset = Object.objects.all()
        resource_name = 'object'
        filtering = {
            "published": ['gte', 'lte', 'exact'],
            }

    def build_filters(self, filters=None):
        if filters is None:
            filters = {}
        orm_filters = super(Object, self).build_filters(filters)

        if('published' in filters):
            published = filters['published']
            # need to do some modifications on the date format here i guess
            qset = (Q(published=published))
            orm_filters.update({'from': qset})

            return orm_filters

    def apply_filters(self, request, applicable_filters):
        if 'from' in applicable_filters:
            from_ = applicable_filters.pop('from')
        else:
            from_ = None

        semi_filtered = super(ObjectResource, self).apply_filters(request, applicable_filters)

        return semi_filtered.filter(from_) if from_ else semi_filtered

更新

我将 build_filter 修改为:

if('published' in filters):
    published = filters['published']
    qset = (Q(published=published) | 
            Q(published__lte=published) |
            Q(published__gte=published))
    orm_filters.update({'from': qset})
    return orm_filters

我收到以下错误:argument of type 'NoneType' is not iterable

所以我猜在过滤时,没有结果。日期格式之间可能有区别吗?

4

1 回答 1

1

您的查询应该在不覆盖任何方法的情况下工作。

class ObjectResource(ModelResource):

class Meta:
    queryset = Object.objects.all()
    resource_name = 'object'
    filtering = {
        "published": ['gte', 'lte', 'exact'],
        }
link: .../api/v1/object/?format=json&published__gte=2012-02-18&published__lte=2013-02-24
于 2013-02-26T23:32:45.703 回答