views:

60

answers:

2

in django 1.1.1, Place.objects.in_bulk() does not work and Place.objects.in_bulk(range(1, 100)) works and returns a dictionary of Ints to Places with indexes - primary keys. How to avoid using range in this situation (and avoid using a special query for ids, I just want to get all objects in this dictionary format)

>>> Place.objects.in_bulk()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.5/site-packages/Django-1.1.1-py2.5.egg/django/db/models/manager.py", line 144, in in_bulk
    return self.get_query_set().in_bulk(*args, **kwargs)
TypeError: in_bulk() takes exactly 2 arguments (1 given)
>>> Place.objects.in_bulk(range(1, 100))
{1L: <Place: "Дом кино">, 3L: <Place: "Михайловский театр">, 4L: <Place: "Киноцентр "Родина"">, 5L: <Place: "Кинотеатр "Аврора"">, 8L: <Place: "Кинотеатр "Художественный"">, 9L: <Place: "площадь Искусств">, 10L: <Place: "Дворцовая площадь">, 11L: <Place: "Александровский сад">, 14L: <Place: "Гранд Отель Европа">}
+2  A: 

This would work:

dict((obj._get_pk_val(), obj) for obj in Place.objects.all())

It is essentially what in_bulk would do without a list of ids.

In most cases you can replace obj._get_pk_val() by obj.pk if you did not mess with the pk names.

Olivier
thanks! I've forgotten Python because of Django :)
valya
A: 

I think you need this:

Place.objects.in_bulk(Place.objects.all().values('id'))
diegueus9
it will produce two queries, which is unnecessary for the task
valya