我有一个简单的模型:
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数据库查询集,我可以通过以下简单方式获得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中限制查询结果的正确和优化方法是什么?
答案 0 :(得分:1)
你可以做这样的事情
results = News.objects.filter(panel = panel).order_by('created')
if results is not None:
new_results = results[:5]