简体   繁体   English

如何连接我现有的外部 PostgreSQL 数据库以自动为 Django Rest 框架创建我的 Models.py?

[英]How can I connect my existing external PostgreSQL Database to automatically create my Models.py for a Django Rest Framework?

I have an existing PostgreSQL Database and I want to create APIs around it using Django Rest Framework.我有一个现有的 PostgreSQL 数据库,我想使用 Django Rest 框架围绕它创建 API。 How do I display the tables in my Database as models in Django to further use them for the API?如何将我的数据库中的表显示为 Django 中的模型,以进一步将它们用于 API?

First of all, you have to connect the existing DB with your Django application by following those instructions https://docs.djangoproject.com/en/3.1/ref/databases/#postgresql-notes or simply add the code below in your settings.py file首先,您必须按照这些说明https://docs.djangoproject.com/en/3.1/ref/databases/#postgresql-notes将现有数据库与您的 Django 应用程序连接起来,或者只需在您的设置中添加以下代码.py 文件

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',                      
        'USER': 'db_user',
        'PASSWORD': 'db_user_password',
        'HOST': '',
        'PORT': 'db_port_number',
    }
}

Secondly, Django provides a powerful command which will help you out to inspect your existing DB models and save those models into your models.py file.其次,Django 提供了一个强大的命令,可以帮助您检查现有的数据库模型并将这些模型保存到您的 models.py 文件中。

python manage.py inspectdb > models.py

In case that you need more information please read the official documentation https://docs.djangoproject.com/en/3.1/howto/legacy-databases/#auto-generate-the-models .如果您需要更多信息,请阅读官方文档https://docs.djangoproject.com/en/3.1/howto/legacy-databases/#auto-generate-the-models

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM