Problem with _unicode () method in django

I am adding the unicode () method to my model, however, when displaying all objects interactively, it does not work.

import datetime
from django.db import models
from django.utils import timezone

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def _unicode_(self):
        return self.question
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def _unicode_(self):
        return self.choice
# Create your models here.

(InteractiveConsole

>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]
+3
source share
2 answers

The django docs show how to specify a unicode method in your model:
https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#other-model-instance-methods

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

Note: These are DOUBLE underscores, where in your example you use only one underscore.

Its a standard python special class method, as stated here

+2
source

__unicode__ ( ). Python, , .

+3

All Articles