Mongoengine query with date range

Kristoffer

I'm trying to retrieve data from mongodb via mongoengine within a specified time span. Below is the db model used.

class DeviationReport(db.Document):
    meta = {'collection': 'DeviationReport'}
    created_at = db.DateTimeField()
    date = db.DateTimeField()
    author = db.StringField()
    read_by = db.ListField(default=[])
    prod_line = db.ReferenceField(ProductionLine)
    product = db.ReferenceField(Product)
    description = db.StringField()

What I've tried is the code below. It does however not return any results. I've used a similar approach when I've needed to build dynamic queries depending on user input.

kwargs = {}
start = datetime.datetime(2018, 12, 11)
end = datetime.datetime(2019, 03, 13)
kwargs['created_at'] = { '$lt': end, '$gt': start }
DeviationReport.objects(**kwargs)

I've obviously made sure that there are objects within the date range, and I've read other similar posts where the query below has been successfully used. How do I get my query to return everything between 'start' and 'end', or how do I rewrite it to do as I wish?

Thanks you.

Kristoffer

I worked around/solved the problem by first getting my results sans date filtering using **kwargs and then filtered that using Q. It may not be optimal, but it works for what I need it to do.

reports = DeviationReport.objects(**kwargs)
reports = reports.filter((Q(date__gte=start) & Q(date__lte=end)))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related