Tsung-Li Wang
Tsung-Li Wang

Reputation: 149

Python3 Objects All Could Not Print Anything

I start a shell with the below command:

python manage.py shell

Then I import my models called Port and User with the below command:

from blog.models import Post
from django.contrib.auth.models import User

After then I have implemented below few commands:

user = User.objects.get(username='ola')
Post.objects.create(author = user, title = 'Sample title', text = 'Test')

At the last, I have implemented below command:

Post.objects.all()

However, I could only get the string as below picture What I got form command Post.objects.all()

Could anyone help me with this? Why couldn't I get the string?

Upvotes: 1

Views: 29

Answers (1)

NixonSparrow
NixonSparrow

Reputation: 6378

You have to set __str__ method in your model:

class Post(...):
    title = models.CharField(...)
    # other fields

    def __str__(self):
        return self.title

Now usually it will print the value of title field.

By default it gives: f"{self.model} object ({self.id})"

Upvotes: 3

Related Questions