7

I am trying to use in_bulk method, although something goes wrong

First I pick values into list that I need to select in bulk:

states = StateObjectRelation.objects.filter(state=int(3), content_type=int(ctype.id))

Then convert them to list:

list = values_list('content_id', flat=True)

Now selecting the items in_bulk:

projects = Project.objects.in_bulk(list)

Give me the following error:

Exception Value:
in_bulk() must be provided with a list of IDs.

If i print out the values that are in list I get the following:

>>> print list
[1L]
>>> print list.values()
[{'state_id': 3L, 'content_id': 1L, 'id': 1L, 'content_type_id': 29L}]
1
  • 12
    list is a name of built-in list type, it's a very bad idea to name variable like that. Commented May 6, 2011 at 10:00

3 Answers 3

9

Firstly, it's a mistake to call your list list, since that's a reserved word (function) in Python. But as for your question, all you need to do is make a list of your query first, like this:

list2 = list(l)

or like this (slower):

list2 = [l for l in list]

Then you really have a real list object, and not just something that appears like one when you print it. Now you should be able to call

projects = Project.objects.in_bulk(list2)

Sign up to request clarification or add additional context in comments.

2 Comments

I'll see whether I can think of something more efficient, but it's not too horrible, and in your case it should be fine. Also, as @vartec mentioned, please change your variable name to something else.
Why not just wrap it in list() ? as in list(values_list('content_id', flat=True)). Obviously you shouldn't call the queryset "list"...
4

I would simply do it like that, using list():

ids = list(your_queryset.values_list('content_id', flat=True))
projects = Project.objects.in_bulk(ids)

Comments

1

I know this has been answered, but these answers seem to be inefficient. The output of a flat values_list() is perfectly acceptable as the list of values for in_bulk()

content_id_pks = StateObjectRelation.objects.filter(state=int(3), content_type=int(ctype.id)).values_list('content_id', flat=True)
projects = Project.objects.in_bulk(content_id_pks)

Note that projects isn't a queryset, it's a dictionary, which presents it's own set of handling problems in re: efficiency.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.