如何在模型更新后使用 Django 从 MySQL 数据库查询数据

问题描述

使用 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 的新手,我不知道自己哪里出错了。

解决方法

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