简体   繁体   中英

django queryset with mongodb

I'm working on a Django app using the tastypie API , I basically want to create objects and then filter them by date so that I know which objects are new ('give me all the objects from that date to today' kind of). I don't know if that matters (I think it does) but I'm using mongoDB.

Where I struggle is when I try to do ?&published__gte=2013-02-01 Simply, what is the most logical way to filter by date? I hope I make any sense, if not don't hesitate to ask me precisions.

Here is my model:

class Object(models.Model):

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

Here is my resource:

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

UPDATE

I modified build_filter to this:

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

I get the following error: argument of type 'NoneType' is not iterable

So I guess that when filtering, there's no result. Is there a difference between date formats maybe?

Your query should work without overriding any method.

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

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