Jean Ureña Jean Ureña - 1 month ago 15
Python Question

Filter by a Reference Property in Appnengine

I am doing a blog in appengine. I want make a query to get the numbers of post by category. So I need filter by a Reference Property in appengine. Look my actual Code.

Those are my models :

class Comment(db.Model) :
user = db.ReferenceProperty(User)
post = db.ReferenceProperty(Blog)
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
date = db.DateProperty(auto_now_add = True)
last_modified = db.DateProperty()
status = db.BooleanProperty(default = True)

class Category(db.Model):
name = db.StringProperty()
date = db.DateProperty(auto_now_add=True)

class Blog(db.Model) :
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
date = db.DateProperty(auto_now_add = True)
category = db.ReferenceProperty(Category)
user = db.ReferenceProperty(User)
last_modified = db.DateProperty(auto_now = True)
status = db.BooleanProperty()
likes = db.IntegerProperty(default = 0)
users_liked = db.ListProperty(db.Key, default = [])
dislikes = db.IntegerProperty(default = 0)
users_disliked = db.ListProperty(db.Key, default = [])


And this is my query :

def numcomments_all_category() :
dic = {}
category = get_category()
for cat in category :
dic[cat.key().id()] = Comment.all().filter("post.category =", cat.key()).ancestor(ancestor_key).count()
return dic


But It seems that filter("post.category =", cat.key()) is not the correct way to do this.

Answer

I haven't used db in a while, but I think something like this will work:

count = 0
# Get all blogs of the desired category
blogs = Blog.all().filter("category =", cat.key())
for blog in blogs:
    # For each blog, count all the comments.
    count += Comment.all().filter("post =", blog.key()).count()
Comments