Our website uses a PHP front-end and a PostgreSQL database. We don't have a back-end at the moment except phpPgAdmin. The database admin has to type data into phpPgAmin manually, which is error-prone and tedious. We want to use Django to build a back-end.
The database has a few dozen of tables already there. Is it possible to import the database schema into Django and create models automatically?
Yes it is possible, using the inspectdb command:
python manage.py inspectdb
or
python manage.py inspectdb > models.py
to get them in into the file
This will look at the database configured in your settings.py and outputs model classes to standard output.
As Ignacio pointed out, there is a guide for your situation in the documentation.
If each table has an autoincrement integer PK then you can use the legacy database instructions.
Related
I have a DB (lets call it data_db) containing some tables. I want to create a dashboard to present data from data_db, so I created a Django project for that purpose.
When I want to get data from one of the tables in data_db, is there a way to do it with Models? (I want Django security management with the DB) or do I have to use raw SQL?
One note: there is existing data in the data_db's table, and I don't want to create a new table with the same exact data on the default Django DB. I also use 2 DBs, Django default's and data_db and I created a database router for data_db to prevent Django from creating all its tables in there.
Thanks.
Yes. In fact Django can even help you create the models. Models that you do not migrate with the help of Django are unmanaged models. These have a managed = False attribute in the Meta class, so something like:
class MyModel(models.Model):
# … fields …
class Meta:
managed = False
If you thus write these unmanaged models, you can make queries with the Django ORM, without Django trying to create new models for these tables.
Of course, specifying models that match with the database is cumbersome. Therefore Django can often construct models based on the tables. You can generate the models with the inspectdb command [Django-doc].
You can generate these models on the stdout with:
python3 manage.py inspectdb
or you can save these to a file through I/O redirection:
python3 manage.py inspectdb > app_name/models.py
I saw lots of information about using multiple databases with one server but I wasn't able to find contents about sharing one database with multiple servers.
Using Micro Service Architectures, If I define a database and models in a django server, named Account, How can I use the database and models in Account server from another server named like Post??
What I'm thinking is to write same models.py in both servers and use the django commands --fake
Then, type these commands
python manage.py makemigrations
python manage.py migrate
and in another server
python manage.py makemigrations
python manage.py migrate --fake
I'm not sure if this would work and I wonder whether there is any good ways.
I doubt this is the best approach, but if you want two separate Django projects to use the same database you could probably create the first like normal then, in the second project, copy over all of the models.py and migration files. Django creates a database table behind the scenes to track which migrations have been applied, so as long as the apps, models, and migration files are identical in the second app it should work without having to fake any migrations.
That said, this sounds like a mess to maintain going forward. I think what I would do is create a single Django project that talks to the database, then create an API in that first project that all other apps can interface with to communicate with the database. That way you avoid duplicating code or having to worry about keeping multiple projects in sync.
When using additional Django servers with the same database that is already managed by the initial Django server, the tables don't need to be managed by the additional servers.
So you can add into the Meta for the models that managed = False and Django will not need to touch them, but can still use them. You will need to copy your models across to the additional servers, or use inspectdb (see below).
from django.db import models
class ExampleModel(models.Model):
id = models.IntegerField(db_column='db', primary_key=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
managed = False
db_table = 'example_table'
You will probably need to state the name of the table being referenced in the Meta as well, otherwise Django may generate a name that doesn't match the database.
You can even cut down the models when using them unmanaged.
It's not necessary to declare all the fields, just the ones you're using.
You can also use python manage.py inspectdb to automatically generate unmanaged models for all the tables in your database, saving time and ensuring the model fields conform to the actual database setup.
This is detailed in the documentation:
https://docs.djangoproject.com/en/4.0/ref/models/options/#managed
https://docs.djangoproject.com/en/4.0/ref/django-admin/#inspectdb
In my project, I have the same case that I have 2 Django servers and 1 database.
I did that I run on server 1
python manage.py makemigrations
and
python manage.py migrate
and on server 2 I just run:
python manage.py makemigrations
I did not run migrate commands on server 2
Now if there is any change on model then I run makemigrations command on both servers and migrate command on any of one server. I am using only one database
I am ready to start a new project with django,and it invloves some operations with database.I have 2 way to get the scheme:
use powerdesigner design the database scheme and output sql,then use python manage.py inspectdb to generate models.
design the model then use python manage.py makemigrations and python manage.py migrate to get the database scheme.
Does someone explain what this 2 ways' difference are and how should I choose?
From inspectdb's documentation:
Use this if you have a legacy database with which you’d like to use
Django. The script will inspect the database and create a model for
each table within it.
Its better if you already have a working DB and want to use django on it. It has limitations like:
If inspectdb cannot map a column’s type to a model field type, it’ll use TextField and will insert the Python comment 'This field
type is a guess.' next to the field in the generated model.
If the database column name is a Python reserved word (such as 'pass', 'class' or 'for'), inspectdb will append '_field' to the
attribute name. For example, if a table has a column 'for', the
generated model will have a field 'for_field', with the db_column
attribute set to 'for'. inspectdb will insert the Python comment
'Field renamed because it was a Python reserved word.' next to the
field.
Also its a shortcut method, not recommended for if you are starting django project.
Also writing models, running makemigration and migrate command will create database scheme containing custom fields such as :
auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
Which are essential for django system if you want to use its authentication backend, User model etc which are core parts of django.
Let's say I have the following table showing how the columns would be declared for a MySQL table: (I can't think of a very realistic example, so here's something that's so silly. This table is created with the help of Excel)
I want to create a model in Django that is compatible with the MySQL table I'll have with the columns declared this way. However, from looking at the Django documentation, I can't find any model field types that in SQL are the same format as those in the picture except for the primary key field.
I did see before that by default, Django handles a database that uses the SQLite Engine, but I want to see if it's possible to handle a database of MySQL tables.
Is there a way to create Django model field types, like MEDIUMINT, TINYTEXT, and SMALLINT, (in MySQL) that are compatible with tables created through MySQL? It's simply a way for me to use the tables that I created myself, not the tables that Django generates automatically once all the models are defined.
In Django you normally create the models and let the framework generate the tables for you. If you have a legacy database you can use python manage.py inspectdb to generate the models from the database (see the documentation). But if it isn't a legacy database and you've created it just now, you are fighting against the framework and making your life more complicated.
I have created a UserProfile field in order to add a favorites functionality to my site. Using Django's recommendation, I created a UserProfile model as follows at the bottom
Unfortunately, I already had the rest of my database created, and so I need to either use a migration utility or manually edit my database. However, I do not have sufficient permissions to utilize a migration utility, so I have to edit the database directly, and am struggling to do so.
This answer is similar to what I want to accomplish, but I can't quite get the syntax to work in my case.
MySQL - One To One Relation?
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
favorites = models.ManyToManyField(Media, related_name='favorited_by')
In my experience, the best migration utility is South. Once you've installed and added it to your settings, you'll need to create initial migrations for your existing modules using
./manage.py schemamigration --initial my_module,
which will include the one containing your UserProfile model, then from there you can migrate using
manage.py migrate my_module.
The real power in using a utility like this is portability and reversibility. You can migrate forward and backward as needed, and you'll be able to bring your schema to virtually any SQL database without all the fuss of rebuilding using SQL directly.
I would certainly agree with Steves recommendation to use South.
However if you for some reason wouldn't want to, you can issue the following command:
python manage.py sql <appname>
This will output the SQL statements which django will use to create your tables. This can then be used to manually modify the database.