0

For example, if i had to select specific ids I can do this using: id_list=[1,4,7]

Blog.objects.filter(pk__in=id_list)

But the problem is id_list is being populated using filters selected in front end. so initially id_list will be empty(id_list=[])

so, is there a way to select all the ids using Blog.objects.filter(pk__in=id_list) when id_list is empty?

Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
Shubham Kumar
  • 105
  • 1
  • 1
  • 8
  • 1
    You can simply do the `if and else` to return queryset with respect to the given value of `id_list`. – dipesh Feb 14 '20 at 11:42
  • @dipesh There can be multiple filters, so if-else won't be a correct approach. – Shubham Kumar Feb 14 '20 at 11:46
  • @ShubhamKumar You only need to handle the case where the list is empty differently. The multiple filters would be contained in `id_list` if there are filters. How is that not a correct approach? – Oluwafemi Sule Feb 18 '20 at 19:42

1 Answers1

0

You can do

if len(id_list) == 0:
     queryset = Blog.objects.all()
else:
     queryset = Blog.objects.filter(pk__in=id_list)
Jack
  • 222
  • 2
  • 12