Query a Django queryset without creating a new queryset?

Not even sure I'm stating the question correctly. Here's the situation. I have a queryset generated by accessing the foreign key relationship. Using the standard Blog/Entry models in the Django documentation, let's say I have selected a blog and now have a set of entries:

entries = Blog.objects.get(id=1).entry_set.all()

So we have some entries for the blog, possibly zero. I'd like to then say construct a calendar and indicate which days have blog entries. So my thinking is to iterate over list of days in the month or whatever, and check the entries queryset for an entry with that date. Question is, what is the best way to do this? My first thought was to do something like

dayinfo = [] # we will iterate over this in the template
for curday in month:
  dayinfo.append({'day':curday, 'entry':entries.filter(day=curday)})

Problem is that the filter call returns a new queryset, and that generates a new sql call for each loop iteration. I just need to pluck the entry object from entries if it exists and stick it into my calendar. So what is the best way to do this? I did get this to work:

dayinfo.append({'day':day, 'entry':[e for e in entries if e.day == curday][0]})

That does not generate new sql calls. But it sure seems ugly.


Resist the urge to put everything on one line - I think the code would be cleaner with something like this:

from collections import defaultdict
calendar = defaultdict(list)

for entry in entries:
    calendar[entry.day].append(entry)

The defaultdict part is simple but you might want to initialize it with all of the days in a month if you're just planning to use a for loop in the template. Also note that if you're using Django 1.1 you can use the new annotate() method to simply calculate the post count if you're not actually planning to generate links to individual posts.

链接地址: http://www.djcxy.com/p/76434.html

上一篇: 如何在django queryset中执行OR条件?

下一篇: 查询Django查询集而不创建新的查询集?