如何限制 Google App Engine 中的 Django-nonrel 查询结果集?
我有一个简单的模型:
class News(models.Model):
title = models.CharField(max_length=255, verbose_name=_("title"))
content = models.TextField(default='', verbose_name=_("content"))
panel = models.CharField(max_length=50, default='', verbose_name=_("panel"))
created = TzDateTimeProperty(auto_now_add=True, verbose_name=_("date created"))
lastmodified = TzDateTimeProperty(auto_now=True, verbose_name=_("date modified"))
我想获取 5 条最近的新闻记录,并且我知道使用 Google App Engine DB 查询集,我可以通过以下简单的方式获取 5 条最近的记录:
results = News.all().filter(panel = panel).order('created').fetch(5)
随着 Django 在 Google App Engine 中运行,我需要这样做:
results = News.objects.filter(panel = panel).order_by('created')[:5]
但是如果没有新闻记录就会抛出异常。我可以将它包装在 catch 异常中,但是在 Django 中限制查询结果的正确且优化的方法是什么?
I have a simple model:
class News(models.Model):
title = models.CharField(max_length=255, verbose_name=_("title"))
content = models.TextField(default='', verbose_name=_("content"))
panel = models.CharField(max_length=50, default='', verbose_name=_("panel"))
created = TzDateTimeProperty(auto_now_add=True, verbose_name=_("date created"))
lastmodified = TzDateTimeProperty(auto_now=True, verbose_name=_("date modified"))
I want to get the 5 recent news records, and I know that with Google App Engine DB queryset I can get 5 recent records in the following easy way:
results = News.all().filter(panel = panel).order('created').fetch(5)
With Django running in Google App Engine I would need to do:
results = News.objects.filter(panel = panel).order_by('created')[:5]
But it will throw exception if there are no news records. I could wrap it within catch exception, but what is the proper and optimized way to limit query results within Django?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以做这样的事情
You can do something like this