2

When using django querysets. Is is possible to use the in operation, or another method, to maintain a one-to-one mapping between objects.

For example I would like:

id_list = [12,2,33] Foo.objects.filter(id__in=id_list)

To preserve order and return None when one of the ids is missing, eg:

ret = [Foo(id=12), None, Foo(id=33)]

where Foo(id=2) doesn't exist.

At present, the only method I have of doing this is to create an intermediate dictionary. For example:

map = {o.id: o for o in Foo.objects.filter(id__in=id_list)}
ret = [map.get(id, None) for id in id_list]
1
  • You could also add a ModelMethod such that something like ret = [Foo.objects.get_or_none(id=id) for id in id_list] would work. Commented Aug 27, 2015 at 14:33

1 Answer 1

2

There isn't a simple way to fetch the instances in the order, and needing to returning None for missing objects makes it even trickier.

You can use in_bulk() to simplify your code slightly.

bulk_foos = Foo.objects.in_bulk(id_list)  # returns a dict of foos, keyed on id
ordered_foos = [bulk_foos.get(foo_id, None) for foo_id in id_list)]
Sign up to request clarification or add additional context in comments.

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.