【发布时间】:2013-01-10 04:17:39
【问题描述】:
我目前正在通过 Django 书籍教程学习 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 导入模型中将我的 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是具体章节的链接!!!
【问题讨论】:
-
你的教程链接是什么?
-
@cathy 帖子上的链接已更新
-
在尝试列出之前,您是否在任何地方调用 save?不知何故,您在某处保存了 2 个额外的副本。也许您之前尝试过保存?
-
我很确定我没有这样做,因为我非常密切地关注本教程,但这可能已经发生了。最困扰我的是 unicode 没有显示任何对象 =/
-
这些肯定是旧的,因为没有 unicode repr,所以没有被清除。
标签: python django django-models model