Programmatically generate Django models for legacy databases - python

I'm trying to find out if there is a way to programmatically generate Django models for legacy databases. So given a list of legacy tables, create a model for each one. Here is an example of what I mean
class Person_001(models.Model):
id = models.IntegerField(primary_key=True)
huge_dataset = models.CharField(max_length=70)
class Meta:
managed = False
db_table = 'person_001'
So for example, create this model for person_001, person_002 etc...
I realize there may be a more efficient way of storing this data and I am opened to suggestions, but the data has been stored this way because huge_dataset is, well, huge.

I think the documentation will help you tremendously here Django Docs
from the docs --
Auto-generate the modelsĀ¶
Django comes with a utility called inspectdb that can create models by introspecting an existing database. You can view the output by running this command:
$ python manage.py inspectdb
Save this as a file by using standard Unix output redirection:
$ python manage.py inspectdb > models.py

Related

Create model for existing database table in django

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.

How to perform a model that represents an existing table or a database view?

I'm trying to create a database view from django instead of associate a model from an existing database table. I'm new in django world and i don't know how how can i do this. Anyone have any ideia where to start look to solve this? Maybe this is not possible but can you see any alternative solution?
I understand how to define a model that as no management, by consider managed=False like i found on django docs, but how can i create an customized SQL view in my model class?
something like this:
Class myModel(models.Model):
Object = models.raw("CREATE VIEW foo AS SELECT * FROM table.A")
class Meta:
db_table = 'myview\".\"mymodeltable'
managed = False
With inspectdb management command, you can obtain the models definition from existing tables. To do that, you need to configure your settings.py file to have access to the database you want to work with and then do:
python manage.py inspectdb > models.py
You will see that it also automatically sets the managed=False. From that point, you can start querying its objects with typical objects.all(), objects.filter() and this stuff
Note: Don't forget to add the app with the imported models to the INSTALLED_APPS variable of your settings.py file.
Unfortunately maybe this is the final answer that can be found on DjangoDocs
This is useful if the model represents an existing table or a database view that has been created by some other means.

MySql to Python Model Creation Tool

I want to migrate a site written in PHP/MySQL to a Python/Django. There will be some significant modifications to the application, but I am not expecting any significant changes to the backend persistence.
Essentially I would like to find a tool that will create the
django.db.models.Model
classes for me. For example consider:
create table blah (
a varchar(10) not null
, b varchar(10) not null
)
and I run the tool and it generates the following models.py file for me
class Blah(models.Model):
a = models.CharField(max_length=10)
b = models.CharField(max_length=10)
Something I can run command line OR wherever. Thanks, and I am new to python/django so I apologize if there is well known solution (although google isn't showing me one).
T
Django can handle it, see inspectdb management command:
Introspects the database tables in the database pointed-to by the NAME
setting and outputs a Django model module (a models.py file) to
standard output.
Also, consider using south for further schema and data migrations.

Django many to many relationship with built in "User" model

Scenario
I have a basic Django app in which users (django's authentication built in model) and reports have a many-to-many relationship.
The Problem
Django does not create a corresponding table to handle this relationship. My application is called reports. There is an error in the admin system upon trying to create a report and assign users to it. It tries to query the table reports_report_users and it fails as it does not exist.
models.py code
from django.db import models
from django.contrib.auth.models import User
class Report(models.Model):
name = models.CharField(max_length=30, blank=False)
users = models.ManyToManyField(User, related_name='reports')
def __unicode__(self):
return self.name
Attempted Solutions
Used this link as a reference: https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/
Ran manage.py syncdb about 300 times - ok, only once, but there were no errors and upon inspecting the SQLite db there were no additional tables created :(
It seems like you've added to the Report model after the first sync. Thus you're dealing with a migration, which django doesn't do natively.
First, Inspect the sql output, make sure that the create table instruction for your many to many relationship is there.
python manage.py sqlall
Assuming the problem is that this is a migration, which django doesn't handle natively, you've got three options:
1) Delete all db tables for this app, then run syncdb again.
2) Manually create the tables (fairly easy to copy paste the create sql from the sqlall command)
3) Start using a migration framework like South.
In the long run you'll appreciate the investment in learning south. In the short term, deleting the DB file is the fastest.-
Have you deleted your db file and run manage.py syncdb again?

Django - syncdb doesn't create tables

I added a many-to-many field to an existing model and was expecting syncdb to create a new table, but there's nothing there. This is what the model looks like:
class Author(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
def __unicode__(self):
return "{0} {1}".format(self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return self.title
Running sql myapp prints the correct statements with the new table, but this is not reflected when I run syncdb. validate also returns no errors. Does anyone know what could be the matter here? Or a better diagnostic?
The syncdb command does not create many to many tables for existing models by design. This decision is explained on ticket 2229.
That leaves you with a few options.
If you don't have any data in your Book model, drop the table and rerun syncdb. Django will recreate the book table and the many to many table.
Use the dbshell command, and create the many to many joining table using the output of sql myapp.
If you're doing multiple schema migrations with Django, make friends with South.
I found this explanation at the django docs useful: SchemaEvolution.
The de facto standard for database migration is Django South.
Its not perfect, but, it works pretty well. You should always check(and edit if necessary) your migration file before running it, to make sure that it actually does what it supposed to do.
You can check out their tutorial here.
Also, if you run:
python manage.py inspectdb > somefile.txt
You can get quickly check out if your database structure is matching your django models.

Categories

Resources