【问题标题】:How to Query data from MySQL database with Django following model update如何在模型更新后使用 Django 从 MySQL 数据库中查询数据
【发布时间】:2021-04-08 04:55:13
【问题描述】:

使用 Django 框架更新 MySQL 数据库中的帖子模型字段后,我无法从数据库中查询帖子。每当我运行命令 python manage.py runserver 时,服务器似乎一切正常。但是,当输入帖子 url 以显示我在更新模型字段之前上传到数据库中的帖子列表时,我得到 1054,“'field list' 中的未知列 'start_post.author_id' 我花了几个小时尝试弄清楚为什么我收到错误但我仍然不明白。在 model.py 中我有:

title = models.CharField()
preamble= models.Charfield()
body = models.TextField()
createdAt = models.DateTimeField(auto_now_add=True, blank=True)

我将上述模型更新为:

title = models CharField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
introduction
 = models.charfield ()
body = models.TextField()
createdAt = models.DateTimeField(auto_now_add=True, blank=True)
    def get_absolute(self):
        return reverse ('post-details', kwarks={'pk': set.pk})

views.py

••••
class PostListView(Listview):
    model = Post
    template_name = 'start/start.html'
    context_object_name = 'posts'
    ordering = ['createdAt']

start.html

•••
{% for post in posts %}
    <h3>{{ post.title }}</h3>
    <i>{{ post.createdAt }} </I>
    <p>{{ post.introduction }}</p>
    <p>{{ post.body }}</p>
{% endfor %}
••••

在更新之前一切正常。但是在更新它之后,我无法从 url start/ 以及帖子详细信息页面访问浏览器上的帖子列表。我在第一个模型中没有作者字段,但我将其添加到更新的模型中。作为 Django 的新手,我不知道我哪里弄错了。

【问题讨论】:

  • 确保运行 python manage.py makemigrations 并在此之后运行 python manage.py migrate ,然后再次运行您的服务器
  • 如果没有帮助,请通过添加 traceback 错误来更新您的问题
  • 我运行了两个命令(makemigrations 和 migrate),迁移成功。我得到的错误是1054, "Uknown column 'start_post.author_id' in the 'field list'

标签: python html django forms mysql-python


【解决方案1】:

在 django 模型中,即使是很小的更改也需要更改数据库(MySql , SQLite , Postgress ,...没关系) 所以如果你改变它并且不运行命令 python manage.py makemigrations 和 python manage.py 迁移 django 将在数据库中查找无法找到的数据库,因为您没有更改它。 所以你只需要在更改模型后运行这些代码

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2021-01-04
    • 1970-01-01
    • 2021-04-06
    • 2020-10-09
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多