Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Primary key id with Column filter in Django ORM

I have a table books in my Postgresql. The below image is how the table structure looks.

enter image description here

Now, I have the book_name "249", and I want to get its corresponding primary key which is 5. Below is the query I am trying to do but Django is throwing an error.

my_book_name = 249

books.model.filter(book_name=my_book_name).get('book_id') # Not Working

Can someone please suggest the right ORM query for getting the corresponding book_id for book_name?

Note:- I deleted PK=4 which is why it's missing in the Column.

like image 399
Mahesh Avatar asked Oct 24 '25 11:10

Mahesh


2 Answers

You can use .values(..) here:

Books.objects.values('book_id').get(book_name=my_book_name)['book_id']

But using .values(..) is often not a good idea. Typically you fetch a Book object into memory, like:

book = Books.objects.get(book_name=my_book_name)
book.book_id  # 5

But even then, it is possible that multiple books (or no books at all) have that name. So you should use .filter(..) to obtain a QuerySet of Books. A QuerySet is a lazy collection, and thus can contain zero, one, or more Book objects here:

books = Books.objects.filter(book_name=my_book_name)
like image 146
Willem Van Onsem Avatar answered Oct 26 '25 01:10

Willem Van Onsem


I don't know why you are using get with filter! Try this

books.objects.filter(book_name=my_book_name).values('book_id')

This will return book_id for all the entries having book_name=my_book_name

like image 39
Ayush Pallav Avatar answered Oct 26 '25 02:10

Ayush Pallav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!