Tuesday, January 2, 2018

Re: How to convert Queryset to String?

On Tuesday, 2 January 2018 09:42:08 UTC, Joshua O. Morales wrote:
Here's the snippet of my code:
models.py:
class Comment(models.Model):
comment_title = models.TextField()
comment_content = models.TextField()
def __str__(self):
return self.comment_content



def test_me():
comment_id_set = list(Comment.objects.values_list('id', flat=True))
for pk in comment_id_set:
comment = Comment.objects.filter(pk=pk)
print(comment)

Output:
<QuerySet [<Comment: Nice weather and location. Not much food choices. The room was fair but clean. Not really fancy. The staff was friendly and helpful. :)>]>
<QuerySet [<Comment: I booked this room for my brother as a gift. They really enjoyed the place.>]>



But your code makes no sense. You do a query to get all the IDs in the database, then for each ID you do yet another query for the ID - using `filter` which returns a queryset, rather than `get` which returns an object - and then print that queryset. Why?

Your code can be simplified to:

comments  = Comment.objects.all()
for comment in comments:
    print comment

--
DR.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1d69081c-f37e-49c4-b145-02efb4e6c1cd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment