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

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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With