How do I generate models for an existing database in Django? - django

I have an existing database I'd like to use with Django. Can I create models based on my existing tables?

This is documented on the Django website:
https://docs.djangoproject.com/en/3.1/howto/legacy-databases/
$ python manage.py inspectdb

You can use inspectdb command.
Like this
python manage.py inspectdb Table_Name --database=DataBaseName >
filename.py
eg: For specific table from specific database()
python manage.py inspectdb Employee_table --database=db_for_employee > models_file.py
Here db_for_employee exist in DATABASE list in settings.py file.
For specific table in default database:
python manage.py inspectdb Employee_table > models_file.py
For all the tables in default database:
python manage.py inspectdb >models_file.py
This would create a file with name models_file.py at your project level and it would contain the models for the existing database.
Note that the if you don't mention the database name then default database from the settings would be considered.
And if you don't mention the table name then all the tables from the database are considered and you'll find models for all the tables in new models.py file
Needless to say that further you'll have to copy the models or the classes created, to the actual models.py file at the application level.

Related

Django migration to delete rows from database

How can I delete rows from a database table with some criteria via a migration script?
Do I need to manually write it or generate it? How to create the file?
You need to create an empty migration file:
python manage.py makemigrations <app_label> --empty
open the generated file and add a new operation:
operations = [
migrations.RunPython(delete_some_rows) # name_of_the_function_to_be_called_to_delete_rows
]
define the function in the migration file:
def delete_some_rows(apps, scheme_editor):
model = apps.get_model('app_label', 'model_name')
model.objects.filter(...).delete()
and simply migrate.

Migration issues in python django?

I have MySQL database in backed but when i change any model i does not reflect in backend
python manage.py makemigration app_name
python manage.py migrate
but it show no migrations applied
does mysql does nor support migrations
my model
class blog(models.Model):
name = models.CharField(max_length=10)
try fake migration
python manage.py -fake app_name
Be sure that you already added app_name to INSTALLED_APPS list

how to switch to a new database

I want to deploy my django project to the production environments, and associated it with an new empty database, and I did as follows :
Create an new empty database
Updated settings.py and pointed the database name to the new one
Deleted the migrations folder under my App
Run python manage.py runserver and no errors returned
Run python manage.py makemigrations and python manage.py migrate
but only auth related tables created ( like auth_user , auth_group ... ), no databases tables created for my Apps
How should I do for this situation to move to the new database for my project?
Deleted the migrations folder under my App
This was your mistake, you deleted the migrations - including the initial migrations. So when you go to makemigrations you haven't got the initial migration available.
So you need to run makemigrations <app_name> to at least get the initial migration.
If you were to do this again, don't delete the migrations, just change the database settings and then migrate.
Firstly, you should not have deleted the migrations. Now, make all the migrations again which you have deleted.
python manage.py makemigrations app_name
Do this for all the apps of which you have deleted the migrations.
Now, add your new database to settings.py. Do not remove the old one yet. For example, if I were adding a MySQL database, I would have added the following to the DATABASES dictionary in settings.py:
'new': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'databasename',
'USER': 'databaseusername',
'PASSWORD': 'databasepassword',
'HOST': 'localhost',
'PORT': '3306',
}
I have named the database as 'new'. Now we have two databases 'default' and 'new'. Now you have to create tables in the new database by running the migrations on the new database:
python manage.py migrate --database=new
You can follow these additional steps if you want to transfer your data to the new database. First, clear the new database:
python manage.py flush --database=new
Now export data from the old database into a json file:
python manage.py dumpdata>data.json
Import this data into the new database:
python manage.py loaddata data.json --database=new
Now you can remove the 'default' database and rename the 'new' database to 'default'.
The procedure mentioned in this answer is taken from my blog.
Just check the output of python manage.py makemigrations command, if it is showing no change detected then you need to check that have you added that app in your INSTALLED_APPS = [] in settings.py file or it might be the problem because you have deleted migration folder.Because if is there any database connectivity error it will show you that while doing makemigrations.
If your database has a new name, i.e. not "default", you need to specify it to migrate:
python manage.py migrate --database <newdb>

Django manage.py - Creating auth_permission and django_content_type tables

I am unable to use syncdb because my app uses some MySQL views. I have run manage.py sqlall <app>, but this does not output the SQL for django_content_type table or the auth_permission tables. I have also had a look into south and django evolution, but they both require syncdb, and I'm not sure they would help anyway.
I have manually added some models to the tables, but this is getting frustrating, and having installed the dbsettings app I am unsure of what I now need to enter.
Does anyone know of a way to get manage.py (or something else) to output the SQL for these tables and their contents?
Thanks.
Having done a bit more digging, I found these:
Fixing the auth_permission table after renaming a model in Django and manage.py sql command for django models - Django.
These output the tables, but not the data:
python manage.py sql auth
python manage.py sql admin
But this gets a lot closer. In the end I managed it with the following:
from django.contrib.auth.management import create_permissions
from django.db.models import get_apps
for app in get_apps():
create_permissions(app, None, 2)
from django.contrib.contenttypes.management import update_all_contenttypes
update_all_contenttypes(interactive=True)
This adds all the permissions and then all the content types which are needed. interactive=True means that it asks you if you want to remove stale content types.
#hajamie solution works for older supported version, taking a hint, below is what worked for me!
django = 1.9.7
from django.contrib.auth.management import create_permissions
from django.contrib.auth.models import Permission
from django.apps import apps
def fix_user_permission():
"""
run this method via shell whenever any amendments in any of the tables is made
"""
print "fixing user permissions"
# delete pre-existing user permission
Permission.objects.all().delete()
apps.models_module = True
create_permissions(apps, verbosity=0)
apps.models_module = None
print "process completed - fixed user permissions"
The easiest solution I found is to install Django Extensions, add it to settings.INSTALLED_APPS and run:
manage.py update_permissions

Django db Table delete

With what command can I delete tables from a django db of a specific app/ only one table?
I did find all sorts of things, but not how to get rid of a table.
Also while I am at this.
I create the models and hit syncdb and then I have the tables.
If I want to update/add to those tables, do I run into problems?
Your best bet would be to get django-south installed in your machine.
if you are using pip, do pip install django-south
This allows you too migrate data forward and backwards.
This is very handy especially if you need to update tables, and new tables etc.
check it out.
adding south to apps are as easy as python manage.py schemamigration appname --initial
Make your changes in a model and run the following python manage.py schemamigration appname --auto
Once your data migration file has been created it'll tell you data is now ready to migrate.
Simply use python manage.py migrate appname
http://south.aeracode.org/docs/about.html
Hope this helps
If you are deleting a table, this is done in the model file of the specific app that you are trying to delete, there is no command for this, you just go into the file and delete it and then re-run syncdb, for your other question, the answer is the same.. every app folder should have a file called "models.py" and here is where the models which are, in this case, equivalent to tables are specified, along with their fields, you simply edit this to make any changes.
def reset():
import install
from django.db.models import get_models
removed_tables = []
exceptions = []
for model in get_models():
if model.__name__ not in ('User','Session','Group','Permission'):
try:
model.objects.all().delete() # So we can remove the table without complaints from the database server.
CURSOR.execute('DROP TABLE %s' % model._meta.db_table)
print "Dropped table %s from model %s" % (model._meta.db_table, model.__name__)
except Exception as e:
exceptions.append([model._meta.db_table, str(e)])
continue
removed_tables.append(model._meta.db_table)
print "Removed %s tables" % len(removed_tables)
syncdb()
install.install() # A function that leads to the creation of my default data