我目前正在通过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>] 另外,我应该将我的models.py从django.db导入模型更改为这个(添加了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是指向特定章节的链接!
发布于 2013-01-26 15:16:15
尝试此示例:
models.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)views.py
def debt(request):
return render(request, 'debt.html', {
'debts': Debt.objects.filter(),
}) debt.html
{% for debt in debts %}
{{debt.user}} - {{debt.name}} <br/>
{% endfor %} 发布于 2013-01-26 15:25:29
这是因为您已经运行了两次代码。这些值已保存在数据库中。当您再次运行它时,又保存了两个值,它们是重复的。
https://stackoverflow.com/questions/14534716
复制相似问题