简体   繁体   中英

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?

{{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.

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.

Convert it into list

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

要解决它,您可以使用嵌套循环(其他循环中的循环)

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

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

now top_post will gives the first object in list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM