0
class Book(models.Model):
    name = models.CharField(max_length=10)


Book.objects.bulk_create([
    Book(name='A'),
    Book(name='B'),
    Book(name='C'),
])


book_names = ['C', 'D', 'A', 'B']

some_func(book_names)
# >>> [Book(name='C'), None, Book(name='A'), Book(name='B')]

When I have a list of values ​​of a specific field of a model object, is there a way to implement a function that returns the model object in the same order in the list and returns None when the value does not exist? I want to implement it using only Django ORM query without using for loop.

preserved = Case(*[When(name=name, then=pos) for pos, name in enumerate(book_names)])
Book.objects.filter(name__in=book_names).order_by(preserved)
# >>> [Book(name='C'), Book(name='A'), Book(name='B')]

In this way, I can get list of objects in the same order, but I don't know how to get None when the value doesn't exist.

  • Already answered [here](https://stackoverflow.com/questions/20489404/django-filtering-by-certain-value-or-none) – Niko Nov 25 '22 at 16:23
  • @Niko You seem to have misunderstood the question :( – Yeongbin Jo Nov 25 '22 at 16:55
  • It seems that I did. I am sorry. Personally I do not know any other way than post processing what you already have, or by using .get() method in order to validate every query using the names in the list. Either way, you are going to need a for loop. – Niko Nov 25 '22 at 18:36

0 Answers0