python - 无法创建条目

标签 python django sqlite

Django 版本 1.10,python 版本 3.4

我在manage.py shell中输入并执行此代码:

from tweet.models import Tweet
tweet = Tweet("Parse JSON like a boss", "Admin")
tweet.save()

并收到错误消息:

invalid literal for int() with base 10: 'Parse JSON like a Boss'

模型.py:

class Tweet(models.Model):
    text = models.TextField()
    pub_time = models.DateTimeField(auto_now_add=True)
    author = models.CharField(max_length=100)

    class Meta:
        ordering = ['-pub_time']

最佳答案

当您没有为模型中的所有字段指定值时,您应该将已有的值作为名称值对发送。

Tweet(text="Parse JSON like a boss", author="admin")

事实上,最佳实践是始终执行此操作,以便将来对模型的更改不会破坏其他地方的代码。这也是 manual 中推荐的方式:

To create a new instance of a model, just instantiate it like any other Python class:

class Model(**kwargs)[source]¶ The keyword arguments are simply the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().

关于python - 无法创建条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38760988/

相关文章:

python - 如何在一次绘制所有 Sprite 时停止 "blinking"的 Sprite

python - Python-根据时间信息(即时,间隔)计算项目之间的相似性

python - 如何在 Django 中提供可下载的 zip 文件

python - 多对多字段 - 访问属性

python - 从 ReactJS 前端访问 Django MEDIA_URL 和 MEDIA_ROOT setting.py 值

android - 共享首选项或文件保存 24 editTexts

Android Studio 从带有 sqlite 的数据库到 GridView 和标题列

python - jinja2 django 模板中的 pgettext

Python Mail 将随机字符转换为 '='

多进程应用程序中的 SQLite 更新 Hook