E. Sutherland
E. Sutherland

Reputation: 111

Django: How to Convert QuerySet into String

I'm using Python 3 and trying to convert a QuerySet into human-readable text. I have a line like this:

top_post = Post.objects.filter(category='1')[:1]

That prints like this:

<QuerySet [<Post: Test Post 1>]>

What makes me scratch my head is a similar QuerySet successfully converts when displayed via a template:

latest = Post.objects.order_by('-published_date')[:5]

"Latest" uses a for...loop in the template:

{% for latest_posts in latest %}
<h1>{{ latest_posts }}</h1>

While "top_post" displays only a blank:

<h1>{{ top_post }}</h1>

Anyone see what's missing?

Upvotes: 3

Views: 18721

Answers (6)

Dilapidus
Dilapidus

Reputation: 425

Just to pile on to last bit about getting the actual value out of the QuerySet objects. This is what I do.

list_of_things = TableName.objects.all().values_list('thing', flat=True)

values_list lets me select what column(s) to return and flat=True extracts (for lack of a better term) each column as an object, thus loading up the list.

Upvotes: 0

shubham suroshe
shubham suroshe

Reputation: 1

If you are using filter then I am assuming you want more than one value else use the get method. You can convert the queryset into a list and then play around the list.

top_post = list(Post.objects.filter(category='1')[:1])[0]

Now top_post will give the first object in the list.

Upvotes: 0

user12741426
user12741426

Reputation: 1

Convert it into list

def 
return(Post.objects.filter(category='1').first)

Upvotes: 0

Sahil Asopa
Sahil Asopa

Reputation: 13

to solve it you can use nested loops (A loop in other loop)

Upvotes: 0

Zahraa Hmayed
Zahraa Hmayed

Reputation: 11

You should implement the __str__ method in the Post model where you define what to print. Moreover you should .get instead of .filter if you expect one object to be returned.

Upvotes: 1

NS0
NS0

Reputation: 6096

{{top_post}} is a query set (slicing a queryset also produces a queryset), so it should display that. When you loop over the queryset, as you do over latest, you display the objects inside.

{{top_post.0}} would give you the object top_post contains.

Alternatively you can use

top_post = Post.objects.filter(category='1').first()

to get the object directly.

Upvotes: 6

Related Questions