获取NDB查询计数的最佳方法-App engine

2024-04-24 13:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

什么是只获取NDB查询结果计数的最佳方法?(读取操作较少)

哪一个更有效地获取NDB查询结果计数?普通查询还是投影查询?以下内容:

EmailSent.query(EmailSent.unsub==True, EmailSent.mail_ref==mail_ref, projection=['to_email']).count()

EmailSent.query(EmailSent.unsub==True, EmailSent.mail_ref==mail_ref).count()

我在这里发现了同样的问题:Get NDB query length - using Python on Google App Engine,但它是为了获得第一个查询结果。


Tags: to方法reftruegetemailcountmail
2条回答

有一个count操作。

https://developers.google.com/appengine/docs/python/ndb/queryclass#Query_count

count(limit=None, **q_options)

Returns the number of query results, up to a limit. This returns the same result as len(q.fetch(limit)) but more efficiently.

使用count。如果你能分页,效率上的差别可以忽略不计。

list_of_emails = EmailSent.query(EmailSent.unsub==True)
total_count = list_of_emails.count()

offset = int(args['offset'])
limit = int(args['limit'])

list_of_emails, next_cursor, more = list_of_emails.fetch_page(limit, offset=offset)

prev_offset = max(offset - limit, 0)
prev = True if offset else False
next_ = True if more else False
next_offset = ''
if next_:
    next_offset = offset + limit

objects = map(lambda emails: func(emails), list_of_emails)
        return {'objects': objects, 'total_count': total_count, 'prev': prev, 'next': next_, 'prev_offset': prev_offset,
                'next_offset': next_offset}

相关问题 更多 >