0

I am working on Django Project with Postgresql database.

I have list of IDs i.e. Column values, I want to extract rows from the database.

Id list :

[238348, 238349, 238350, 1000]

(Id rang is not in sequence.)

For Single id value:

>>> page.objects.filter(id=238348)
[<page: o-0238348>]

I can use for loop to Iterate every ID and get row, but is there is any method like OR to extract rows?

Edit: done

We can use in:

Demo:

>>> page.objects.filter(id__in=[238348,238349, 1])
[<page: o-0238349>, <page: o-0238348>]
rnevius
  • 26,578
  • 10
  • 58
  • 86
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
  • 1
    possible duplicate of [django filter with list of values](http://stackoverflow.com/questions/9304908/django-filter-with-list-of-values) – rnevius Mar 30 '15 at 10:02

3 Answers3

1

You're looking for the in field lookup:

page.objects.filter(id__in=[238348, 238349, 238350, 1000])
rnevius
  • 26,578
  • 10
  • 58
  • 86
1

Indeed is in a solution, other way is using Q-objects. See https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q-objects for documentation.

Blackeagle52
  • 1,956
  • 17
  • 16
  • Yes, Thank You. It is working with `in`. I checked after posting question. +1 – Vivek Sable Mar 30 '15 at 09:56
  • Yes, I saw when I posted my answer, but gave you another alternative, I thought `OR`s could be faster than `IN`, but http://stackoverflow.com/questions/3074713/in-vs-or-in-the-sql-where-clause says `IN` is a bit faster (for MySQL), so disregard the answer. – Blackeagle52 Mar 30 '15 at 10:02
0

It is work by in:

Demo:

>>> page.objects.filter(id__in=[238348,238349, 1])
[<page: o-0238349>, <page: o-0238348>]
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56