0

我目前正在通过 Django-book 教程学习 Django,但遇到了一个错误。在第 5 章,我应该在 python 解释器中输入这个

    >>> p1 = Publisher.objects.create(name='Apress', 
    ... address='2855 Telegraph Avenue', 
    ... city='Berkeley', state_province='CA', country='U.S.A.', 
    ... website='http://www.apress.com/') 
    >>> p2 = Publisher.objects.create(name="O'Reilly", 
    ... address='10 Fawcett St.', city='Cambridge', 
    ... state_province='MA', country='U.S.A.', 
    ... website='http://www.oreilly.com/') 
    >>> publisher_list = Publisher.objects.all() 
    >>> publisher_list 

根据教程,我应该得到一个输出

    [<Publisher: Publisher object>, <Publisher: Publisher object>] 

但是我得到了相同的输出,但是有 4 个对象!!

    [<Publisher: Publisher object>, <Publisher: Publisher object>, <Publisher: Publisher object>, <Publisher: Publisher object>] 

另外我应该从 django.db import models 将我的 models.py 更改为这个(添加的 unicode 函数)

    class Publisher(models.Model): 
    name = models.CharField(max_length=30) 
    address = models.CharField(max_length=50) 
    city = models.CharField(max_length=60) 
    state_province = models.CharField(max_length=30) 
    country = models.CharField(max_length=50) 
    website = models.URLField() 

    def __unicode__(self): 
            return self.name 

    class Author(models.Model): 
    first_name = models.CharField(max_length=30) 
    last_name = models.CharField(max_length=40) 
    email = models.EmailField() 

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

    class Book(models.Model): 
    title = models.CharField(max_length=100) 
    authors = models.ManyToManyField(Author) 
    publisher = models.ForeignKey(Publisher) 
    publication_date = models.DateField() 

    def __unicode__(self): 
            return self.title 

为了显示对象。这是根据教程的输出

    >>> from books.models import Publisher 
    >>> publisher_list = Publisher.objects.all() 
    >>> publisher_list 
    [<Publisher: Apress>, <Publisher: O'Reilly>] 

但我仍然得到

    [<Publisher: Publisher object>, <Publisher: Publisher object>, <Publisher: Publisher object>, <Publisher: Publisher object>] 

不知道为什么我得到更多的对象,为什么我不能查看 unicode 的输出......

感谢您的帮助!

**http://django-book.readthedocs.org/en/latest/chapter05.html 是具体章节的链接!!!

4

2 回答 2

2

试试这个示例:

模型.py

class Debt(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=50,
        help_text="Name to identify your debt.")
    due_day = models.PositiveSmallIntegerField(
        help_text="Day of the month payment is due.")

    def __unicode__(self):
        return "{0}".format(self.user)

视图.py

def debt(request):

return render(request, 'debt.html', {
    'debts': Debt.objects.filter(),
}) 

债务.html

 {% for debt in debts %}
     {{debt.user}} - {{debt.name}} <br/>
 {% endfor %}  
于 2013-01-26T07:16:14.870 回答
0

这是因为您已经运行了两次代码。这些值已经保存在数据库中。当您再次运行它时,将保存另外两个值并且它们是重复的。

于 2013-01-26T07:25:29.293 回答