views:

950

answers:

4

What would be the App Engine equivalent of this Django statement?

return Post.objects.get(created_at__year=bits[0], 
       created_at__month=bits[1], 
       created_at__day=bits[2],
       slug__iexact=bits[3])

I've ended up writing this:

Post.gql('WHERE created_at > DATE(:1, :2, :3) AND created_at < DATE(:1, :2, :4) and slug = :5',
    int(bit[0]), int(bit[1]), int(bit[2]), int(bit[2]) + 1, bit[3])

But it's pretty horrific compared to Django. Any other more Pythonic/Django-magic way, e.g. with Post.filter() or created_at.day/month/year attributes?

A: 

Ended up using the relativedelta library + chaining the filters in jQuery style, which although not too Pythonic yet, is a tad more comfortable to write and much DRYer. :) Still not sure if it's the best way to do it, as it'll probably require more database processing time?

date = datetime(int(year), int(month), int(day))
... # then
queryset = Post.objects_published()
                            .filter('created_at >=', date)
                            .filter('created_at <', date + relativedelta(days=+1))
                            ...

and passing slug to the object_detail view or yet another filter.

Jerry Chong
+1  A: 

You don't need 'relativedelta' - what you describe is a datetime.timedelta. Otherwise, your answer looks good.

As far as processing time goes, the nice thing about App Engine is that nearly all queries have the same cost-per-result - and all of them scale proportionally to the records returned, not the total datastore size. As such, your solution works fine.

Alternately, if you need your one inequality filter for something else, you could add a 'created_day' DateProperty, and do a simple equality check on that.

Nick Johnson
+3  A: 

How about

from datetime import datetime, timedelta

created_start = datetime(year, month, day)
created_end = created_start + timedelta(days=1)
slug_value = 'my-slug-value'

posts = Post.all()
posts.filter('created_at >=', created_start)
posts.filter('created_at <', created_end)
posts.filter('slug =', slug_value)

# You can iterate over this query set just like a list
for post in posts:
    print post.key()
jgeewax
A: 

By the way you could use the datetime.timedelta. That lets you find date ranges or date deltas.

cheers Sri

Sri