开发者

Following ForgeinKeys in Django's select_related to populate a *_set variable?

I have some simple 开发者_运维知识库Django Models like this:

class Event(models.Model):
    # some stuff

class Price(models.Model):
    event = models.ForgeinKey(Event)

i.e. each Event has 1 or more Price's.

I am selecting some Events like this: events = Event.objects.filter(…), and then looping over them for event in events:, inside the loop I need to access all the Price objects for each event (i.e. with event.price_set), however that does a new SQL query for each event. I have thousands of events, and this is causing thousands of queries. Is there some way I can prepopulate the price_set for each event all in one go?

I tried adding a select_related to the QuerySet, but it doesn't work (I can still see all the queries in the Django Debug Toolbar). Surely there's some way to do a join on the original SQL query which will bring in all the Event's and their Prices in one query?


Have a look at: https://github.com/lilspikey/django-batch-select/ It will allow you to get what you want with just 2 queries (1 for the events and 1 for the prices)


As a hint to other people with this problem:

Django 1.4 (not yet released at the time of writing), has prefetch_related as a complement to select_related, which does exactly what I'm asking for here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜