5

How to retrieve the data from Django queryset for use in a variable

When an output is received in below form after running the query

<QuerySet [{'name': 'John'}]>

I want to use the value 'John' in a variable for further processing.

How do I extract this ?

2
  • 1
    But this is a collection of values, so it is, stricty speaking possible that this queryset contains zero, one, or more entries. If you filter such that there is always exactly one element, you should use Model.objects.get(pk=my_pk). Commented Feb 21, 2019 at 20:01
  • Thanks Willem, So I am using filter and it may get me more than one names. So given the above format of output, How do I get the names out of it ? Commented Feb 21, 2019 at 20:10

3 Answers 3

5
k = <QuerySet [{'name': 'John'}]>
k[0] = {'name': 'John'}

Queryset is a list.

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

Comments

2

Try with values_list().

myValues = myQuerySet.values_list()

Comments

0

One way to do is to use a for loop:

>>> names = Student.objects.filter(first_name__in=['Varun', 'Gina'])
>>> names
<QuerySet [<Student: Varun Sharma>, <Student: Gina Ram>]>
>>> for name in names:
...     print(name)
... 

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.