1

Scenario

Lets say i have a model book with fields:

  • id
  • name
  • author
  • rating

(Keeping it simple :) )

Now lets say we have multiple rows of books in our db.


Question

How can I query the db to receive a array of Book objects who have the same author for instance?

array = Book.objects.filter(author='JK Rowling') --> returns a QuerySet But i want an array of Book objects.

[{id:1, name:'HP 1', author: 'JK Rowling'},{id:2, name:'HP 2', author: 'JK Rowling'},{id:3, name:'HP 3', author: 'JK Rowling'}]

2 Answers 2

1

A queryset is an array of Book objects. What you're showing there is a list of dictionaries, which is something else entirely. You can achieve that by using values():

Book.objects.filter(author='JK Rowling').values()

Note that by doing this you lose all the functionality associated with returning the actual Book objects themselves, such as the ability to call their methods, modify and save them back to the db, etc. Unless you have a really good reason, you should stick to the actual queryset.

Sign up to request clarification or add additional context in comments.

Comments

0

You can build a dictionary from an arbitrary object by using the __dict__ special method.

A comprehension of the queryset will allow you to build a list of these dictionaries.

e.g. queryset = Book.objects.filter(author='JK Rowling') array = [book.__dict__ for book in queryset]

1 Comment

This is unlikely to be useful. For example, it would include internal attributes like _state which OP almost certainly doesn't want in their dict representation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.