1

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?

4

1 回答 1

1

你可以做这样的事情

results = News.objects.filter(panel = panel).order_by('created')
if results is not None:
   new_results = results[:5]
于 2011-05-24T04:47:49.627 回答