如何在没有表单的Django中创建模型实例对象

问题描述 投票:0回答:1

这里是django的新手。我正在按照此文档链接创建模型的实例https://docs.djangoproject.com/en/2.2/ref/models/instances/#creating-objects,我想念一些东西。这是我的代码

#models.py
class Book(models.Model):
    title = models.CharField(max_length=100)

    @classmethod
    def create(cls, title):
        print('print title:')
        print(title)
        book = cls(title=title)
        # do something with the book
        return book

#forms.py
book = Book.create("Pride and Prejudice")
print('printing DJANGO--------------')
print(book)

#console output
print title:
Pride and Prejudice
printing DJANGO--------------
Book object (None)

我从字面上复制了本教程中的代码,但没有做任何更改。我在做什么错?

感谢

django django-models
1个回答
0
投票

从我的观点来看,一切都很好。只需添加book.save(),您就会看到一个ID,而不是None

© www.soinside.com 2019 - 2024. All rights reserved.