我目前正在学习Django虽然是Django-book教程但我遇到了一个错误。 在第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是特定章节的链接!!!
答案 0 :(得分:2)
试试这个样本:
<强> 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 %}
答案 1 :(得分:0)
这是因为你已经运行了两次代码。值已保存在数据库中。再次运行时,会保存另外两个值,它们是重复的。