Praful Bagai
Praful Bagai

Reputation: 17372

Django - Return none object if record not found given the queried list

I've a list of ids [1,2,3,4,5,6,7,8,9,10]

Now I want to query a model with the above list of ids. This is how I perform the operation.

ModelA.objects.filter(id__in=ids)

This returns objects of ModelA which match the given id list. Now consider ids [2,3,5] were not present. Can I get a queryset of same length as that of the input list, including all the non-found objects as well.??

For eg:-

if [2,3,5] are not found, it should return

[1,None,None,4,None,6,7,8,9,10]

How can I achieve it?

Upvotes: 1

Views: 888

Answers (1)

Alex
Alex

Reputation: 1522

You can do something like...

ids = [1,2,3,4,5,6,7,8,9,10]
results = ModelA.objects.filter(id__in=ids)
result_ids = [result.id for result in results]
return [id if id in result_ids else None for id in ids]

Upvotes: 4

Related Questions