0

This code is from models.py in my App called article

from django.db import models

# Create your models here.

class Article(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField('date published')
    likes = models.IntegerField()


    def __unicode__(self):
        return self.title

I've added 3 objects into the db like this

>>> from django.utils import timezone
>>> a = Article(title = "Test 1", body = "blah blah blah " ,pub_date=timezone.now(),likes=0)
>>> a.save()
>>> a.id
1
>>> a = Article(title = "Test 2", body = "blah blah blah " ,pub_date=timezone.now(),likes=0)
>>> a.save()
>>> a.id
2
>>> a = Article(title = "Test 3", body = "blah blah blah " ,pub_date=timezone.now(),likes=0)
>>> a.save()
>>> a.id
3
>>> Article.objects.all()
<QuerySet [<Article: Article object>, <Article: Article object>, <Article: Article object>]>

whenever i called Article.objects.all() method it returns me the title in object form. From the documentation the unicode method must return me the actual title in the string form.

I'm new to Django and i've tried alot changing the unicode method but nothing seems to work. Thanks you in advance

here is the output I am getting

 from article.models import Article
>>> Article.objects.all()
<QuerySet [<Article: Article object>, <Article: Article object>, <Article: Article object>]>

and the output i want

<QuerySet [<Article: Article Test 1>, <Article: Article Test 2>, <Article: Article Test 3>]>
Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
  • Are you using python 2 or 3? If you are using python 3 use the __str__() method instead of __unicode__(). – wobbily_col Feb 19 '17 at 13:59
  • little more background information: [python-str-versus-unicode](http://stackoverflow.com/questions/1307014/python-str-versus-unicode) – Nrzonline Feb 19 '17 at 14:38

1 Answers1

2

You need to change def __unicode__(self): to def __str__(self): as unicode version is used in Python2 and str in Python3

TitanFighter
  • 4,582
  • 3
  • 45
  • 73