English 中文(简体)
Trouble with _unicode() methods in django
原标题:Trouble with _unicode() method in django
  • 时间:2012-05-10 18:25:28
  •  标签:
  • django

我在模型中添加“unicode(>)”方法,但在显示所有物体在互动中不发挥作用时。

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>]
最佳回答

The django docs show you 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)

<>说明: 这些是DOUBLE强调的,在你的例子中,你只是使用单一强调。

http://docs.python.org/fer/datamodel.html#object.__unicode__"rel=“nofollow”

问题回答

它们需要的名称是unicode__(两面强调)。 这是对沙尔保留方法的粗略细节,从看看不出。





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签