Reputation: 1333
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.
Upvotes: 4
Views: 5637
Reputation: 477617
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 Book
s. 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)
Upvotes: 4
Reputation: 1057
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
Upvotes: 3