Create model for existing database table in django - python

I have an old table in the database. And I want to create a model in Django application.
After creating a model and I used migrate command then it created a new table with its own name.

Django provides a utility to auto-generate models from an existing database via inspectdb command.
You can create models by introspecting an existing database by executing following command
python manage.py inspectdb
The above command will output all the models Django can create from the existing database to stdout. You can save this as a file by using standard Unix output redirection
python manage.py inspectdb > models.py # or pass the app_name.models.py if you want to generate them inside models.py file of specific app
The output file will be saved to your current directory. Move that file to the correct app and you have a good starting point for further customization.
you can refer https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-inspectdb for more information.

You can specify the table name by setting table on the model's Meta class. Set managed = False to prevent Django from creating the table.
class ExistingModel(models.Model):
...
class Meta:
table = 'existing_table'
managed = False
After making these changes, I would revert the previous migration, remove the migration file, then run makemigrations again.

Related

Switch to another database in Django

I have a django project that was created on an Oracle database and I want to switch to ANOTHER Oracle database. I have followed this tutorial https://pythonfusion.com/switch-database-django/, but there is a problem that not all models are created initially in Django, some are created using inspectdb on existing tables in other databases . Therefore, when using the migrate --database=new command, I get errors about those tables that already existed before Django was created. Is there a way to migrate only the models and tables necessary for Django to work? (users, auth...)
I think you have to take a look at the managed attribute of each model meta class.
If managed is true then django will change the model in the database.
Unmanaged model :
class MyModel(models.Model):
...
class Meta:
managed = False # This means django will ignore MyModel when migrating
Managed model :
class MyManagedModel(models.Model):
...
class Meta:
managed = True # This means django will migrate MyManagedModel
More documentation here : https://docs.djangoproject.com/en/4.1/ref/models/options/
Yes you can definitely customize your migration behavior, the command python manage.py makemigrations creates a couple of files that are used to migrate your models into your DB, any who you can still access these files and choose exactly what to include, exclude and even edit them.
Check the following link:
https://dev.to/koladev/writing-custom-migrations-in-django-3eli
If I've understood your question correctly, then you're looking to use Django's built-in migrations. To find out which migrations have been run against your new database, run the command manage.py showmigrations --database=new which will show you a list of all migrations that exist within the context of your application.
Once that is done, you can manually run the desired migrations (e.g. auth and contenttypes) by running the command manage.py migrate --database=new app_label migration_name.
showmigrations command: https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-showmigrations
migrate command: https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-migrate

How to use Django with an existing database in MySQL?

I have an application in Django 2.0 and as a database engine I use MySQL. I have a problem because the database was previously created and already has records, my idea is to use this same database for the application I am creating.
Use the command
python manage.py inspectdb > models.py
To create the models.py file which will be cleaned as indicated by the models.py file that was generated.
#This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
After this I proceed to execute:
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
But it generates the following error:
(1050, "Table 'XXXXXXX' already exists")
Obviously it tells me that the table already exists, but how do I not generate this error and continue administering the tables from Django.
You need to run --fake-initial or --fake. See more at Django migrations. Be careful because running inspectdb doesn't solve all your problems. You need to fix the things inside models.py manually and migrate again.
One of the things (and the main reason I do not use Django) is it likes to take control of everything. The fact that it controls the database means that if you don't start strictly in Django, you are doing it wrong.
However there is a work around:
https://docs.djangoproject.com/en/2.0/howto/legacy-databases/

How to change Django's default Postgres database search directory

I am creating a Django web application and I am using Postgres for my database.
Under my project, I have a web application named 'home', and I created a table named 'myTable' in Postgres.
Whenever I try to save something in the table, Django automatically looks for the table called 'home_myTable' instead of 'myTable'. For example, if I do
python manage.py migrate
I get the following error:
django.db.utils.ProgrammingError: relation "home_myTable" does not exist
I have been working around this by manually giving Postgres commands using Psycopg2, but this is really annoying.
Is there a way to stop Django from automatically start looking for 'home_myTable' and instead make it search the table that I want?
You can set the db_table Meta option for you model.
class MyTable(models.Model):
...
class Meta:
db_table = 'mytable'
Unless you are dealing with a legacy database, I recommend that you define your models, create migrations, then let Django create the tables, instead of creating the tables manually as you are doing.

Ignoring existing table when ./manage.py migrate

I have a question about Django's migration feature when there is an existing table.
ContentData
ContentType
Faq
UserLog
TB_TEAM_INF
When I try to do "./manage.py migrate" so it can create the 5 tables above from models.py, I got an error message because there is an existing table, TB_TEAM_INF.
Since TB_TEAM_INF is a table being used by another team, I cannot remove the table. I cannot use a separated database either due to constraints of the project. In this case I open the migration file like 0001_initial.py and manually remove the model object, TB_TEAM_INF temporarily during migration.
Is there a better way to ignore existing tables when "./manage.py migrate" rather than manually editing the migration file?
I tried --exclude=TB_TEAM_INF or --ignore=TB_TEAM_INF option with ./manage.py migrate but it seems those options are not accepted. I am using Django 1.7.2.
Add the managed option to your model definition:
class TB_TEAM_INF(models.Model):
...
class Meta:
managed = False
Excerpt from the documentation:
If False, no database table creation or deletion operations will be performed for this model.

How to change a sqlite table column value type from Django model?

I created a table before I code the Django app and now I merged both the app and the table with following command python manage.py inspectdb > models.py. However after some while I really need to change the value type of one of the column. Is it enough to chage it through the model file or do I need some additional steps?
If you change a field in a Django model, Django itself doesn't know how to update your database accordingly (syncdb only add tables from new models).
You have two options:
manually create your database tables;
use a migration tool like South that detects and generates migration files from changes made to your models;
I recommend the second option as it's programmatic, more error-proof and makes your life easier when you need to go back and forth between database schemas.
There is an easy way to do this. (in Django 2)
After making the necessary changes to the model.py file of your app, run command:
python manage.py makemigrations - This will generate a new file in migration folder of your app.
python manage.py migrate - This will apply those edits on actual databse.
To check if the changes have been applied, run command : .schema <tablename> in your terminal, after entering the sqlite command-line program.

Categories

Resources