How to remove the name "Queryset" from queryset data that has been retrieved in Django Database?

Viewed 284

we all know that if we need to retrieve data from the database the data will back as a queryset but the question is How can I retrieve the data from database which is the name of it is queryset but remove that name from it.

maybe I can't be clarified enough in explanation so you can look at the next example to understand what I mean:

AnyObjects.objects.all().values()

this line will back the data like so:

<QuerySet [{'key': 'value'}]

now you can see the first name that is on the left side of retrieving data which is: "QuerySet" so, I need to remove that name to make the data as follows:

[{'key': 'value'}]

if you wonder about why so, the abbreviation of answer is I want to use Dataframe by pandas so, to put the data in Dataframe method I should use that layout.

any help please!!

2 Answers

You don't have to change it from a Queryset to anything else; pandas.DataFrame can take any Iterable as data. So

df = pandas.DataFrame(djangoapp.models.Model.objects.all().values())

Gives you the DataFrame you expect. (though you may want to double check df.dtypes. If there are Nones in your data, the column may end up to be of object type.)

You can use list(…) to convert it to a list of dictionaries:

list(AnyObjects.objects.values())

You will need to serialize it with the json package to obtain a JSON blob, since strings with single quotes are not valid JSON, in order to make it a JSON blob, you can work with:

import json

json.dumps(list(AnyObjects.object.values()))
Related