如何访问 Django 中 mysql 数据库中的 table?

How to access a table which is present in mysql database in django?

我是一名 Django 初学者,现在我遇到了一个问题——我正在尝试访问 mysql 数据库中已经存在的 table 现在我想渲染html 页面上的 table,如何访问 table 并将其呈现在 html 页面上

您可以让 Django 检查您的数据库 table 并为其输出一个模型,其中:

python manage.py inspectdb

如果你想保存输出,你可以将它重定向到一个文件中,这样你就可以编辑它,因为 Django 的 inspectdb 对你来说可能不够准确,就像这样:

python manage.py inspectdb > models.py # make sure models.py does not exist before you run that!

然后在编辑您的模型后,您可以像使用任何其他模型一样使用它。如果你不想让 Django 管理它(即不应用迁移),你可以在你的模型上设置 managed = False:

class YourModel(models.Model):
    .... your fields ....

    class Meta:
       managed = False

然后将您的模型渲染成 HTML,您可以像使用任何其他模型一样使用它。因此,创建视图、url 和模板。如果您不知道该怎么做,您可能需要学习教程:

https://docs.djangoproject.com/en/3.2/intro/tutorial01/

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website

关于 inspectdb 的更多信息: https://docs.djangoproject.com/en/dev/howto/legacy-databases/