I have an existing PostgreSQL Database and I want to create APIs around it using Django Rest Framework. How do I display the tables in my Database as models in Django to further use them for the API?
1 Answer
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
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.
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.
2 Comments
Prateek Jain
When I'm trying to migrate these models, I am getting this error: "ERRORS: api.AddressMaster.address_owned_by: (fields.E304) Reverse accessor for 'AddressMaster.address_owned_by' clashes with reverse accessor for 'AddressMaster.address_type'. HINT: Add or change a related_name argument to the definition for 'AddressMaster.address_owned_by' or 'AddressMaster.address_type'." For all my DB Tables, how do I tackle these? And also "AssertionError: Model api.Holidays can't have more than one auto-generated field." for all my auto-generated Primary Keys
Panos Angelopoulos
hey @PrateekJain those issues are unrelated to your current question, you can dig into each of them by researching further in the web.