sqlite configuring with django - python

I have been assigned the task of setting up an online database with sqlite via django- where it will contain columns of information. My problem is that I can't figure out which is establishing table where the information will go- my models.py script or should I do it with a "CREATE TABLE" command?
An example of the code in my models.py script is below:
class Person(models.Model):
firstname=models.CharField(max_length=100)
lastname=models.CharField(max_length=100)
The tutorial that I was given recommended this command:
insert into freezer_person (firstname,last name) values('Louis','Pasteur')
However upon executing this command I naturally got an error saying "table does not exist" i.e. I have to use the "CREATE TABLE" command.
so when I tried:
"CREATE TABLE in freezer_person(...)"
It returned that "in" was syntactically incorrect.
So my question is how do I go about creating a table that will intake info from models.py?- I can't seem to find any info on this...

You don't create the tables; Django does it for you, through the migrations system.
This is all fully covered in the tutorial.

Your model classes from models.py define your tables: each model class will be transposed in a table. Each property of a model class will be a column in the corresponding table. Each instance of the model class will be a row in that table.
So when you want to create a table you define a model class in the models.py file of your app, then run
python manage.py makemigrations
which tracks the changes made to the model class and generate a migration file which contains the sql statements to be applied to the database, and then to apply them to the database, you run
python manage.py migrate

Related

python manage.py inspectdb > models.py dont work in existing mongo database

sample_data is the name of the mongo collection.
At first, I created a model class named sample_data because I thought it will just read what's already existing in my mongodb but the result was... It creates a new collection named {{MyDjangoAppName}}_sample_data so I search on google "Integrating Django with a legacy database", then tried it to generate the model for me but unfortunately it replaces my models with the error message and looks like this...
I added a picture of my terminal with the error message below. Is it about the mongo ObjectId?
How can I exclude the objectId here and generate a new id? Is that possible?
Should I stick on manually creating the models in models.py and rename the collection name of the existing database?
What is the right approach for this?

Django Models Field.E340 : ManytoMany relationship same intermediate table name in 2 different apps

We are trying to makemigrations and migrating the app level model to respective databases using database router.
We have one model file in one app pointing to one database and same structured models with table name with some tables added are being created in other app then intermediate table name is creating error.
Error : master.LegalTbl.legal_field_name: (field.E340) The field's intermediary table 'tbl_legal_tbl' clashes with the table name of 'user.LegalTbl'.
I'm not sure may be it could work:
delete the migration file that has conflict.
add Class Meta to your model which name you want to change
meta class have one attribute called db_table write table name
Now you can run makemigrations and migrate, it will solve your conflict i guess

Django automatically create primary keys for existing database tables

I have an existing database that I'm trying to access with Django. I used python manage.py inspectdb to create the models for the database. Currently I'm able to import the models into the python shell however when I try to access any of the actual objects in any way, I get this error OperationalError: (1054, "Unknown column 'some_table.id' in 'field list'"). I see that the table in the database in fact does not have an id field. How can I fix this? Do I need to update the managed field in the Meta class and run a migration so it can create this field automatically?
From the Django documentation: This feature is meant as a shortcut, not as definitive model generation. See the documentation of inspectdb for more information. (Reference: https://docs.djangoproject.com/en/1.8/howto/legacy-databases/)
You're going to need to manually clean up the models and migrate. The line you'll have to add for adding the "id" field is:
id = models.IntegerField(primary_key=True)
Warning: I'd definitely create a copy of the database to toy with, rather than the original. This will likely take you some trial and error to get right. After you're absolutely sure you have it right, you can changed Managed=True, but be VERY careful!

"DatabaseError, column does not exist". But shows in my manage.py sql

Regarding Django & Python:
The Error:
Exception Type: DatabaseError
Exception Value:
column objects_thing.name_id does not exist
LINE 1: ...s_thing"."created", "objects_thing"."modified", "objects...
In my manage.py sql objects
CREATE TABLE "objects_thing" (
otherstuff,
otherstuff,
"name_id" integer NOT NULL REFERENCES "profiles_name" ("id"),
otherstuff,
);
So it clearly exists.
I've ran syncdb.
Why am I getting this error? And how do I go about fixing it? (I'm a newbie to all of this) Thank you in advance for the help.
EDIT:
Thing Model:
class Thing(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
name = models.ForeignKey(Name)#The name for this thing
current_allocation = models.DecimalField(max_digits=13, decimal_places=2, null=True, blank=True)
target_allocation = models.DecimalField(max_digits=13, decimal_places=2, null=True, blank=True)
placeholder = models.ForeignKey(Entity, null=True, blank=True, on_delete=models.SET_NULL)
avatar = models.ImageField(upload_to='avatars/thing/', null=True, blank=True)
syncdb doesn't change existing tables in your database, so if you run that, and then change your model, your model is now out of sync with the table it represents. Running syncdb again will not fix that.
You either need to use something like south to do a migration, delete the table from your DB so that syncdb will recreate it, or manually run an ALTER TABLE on your DB.
EDIT (greater detail)
When you create a subclass of Model in models.py, it acts as a representation of a database table, but doesn't automatically have a database table. You get that by running python manage.py syncdb. Django, then, looks through all your models.py files, generates the SQL required to actually create a table like that and then runs it on your database. The end result is that you end up with actual database tables that are tied to your models.
However, syncdb only creates tables. It does not alter them. So, if you go and change one of your models (add a field, change the name of a field, etc.), nothing has happened at the database level. Running syncdb again will not help, either, because there's no new tables to create. You have to somehow get the table to match the model and vice versa, though, so that's where your options come in:
Use South (link above). South enables you to create migrations, so when you change something on your models you can run:
python manage.py schemamigration --auto yourapp
And it will generate code that will alter the table to match your model. You then need only apply the migration with:
python manage.py migrate yourapp
And you're done. The table now matches your model and all is right in the world again.
You can manually delete the table from your database. You wouldn't want to do this in production because all the data in that table will go along with it, but in development it shouldn't be a problem. After the table is gone, you can then run:
python manage.py syncdb
Because, the table no longer exists, Django will create it, but it will create it based on your current model's state. The net result is the same, your model and table match, so you're good to go.
You can manually alter the table. This requires that you figure out what SQL needs to be applied to change the table to match your model. You run this SQL on your database, and then the table is in parity with the model.
The point is that somehow, someway, you must update the table to reflect any changes you make to your models. The model isn't the table, it's just a programmatic representation of it.
The column might not necesarrily exist. The sql command just shows the sql used to create it, It is based on your current model. You could delete the table and re syncdb or manually add the column. https://docs.djangoproject.com/en/dev/ref/django-admin/#sql-appname-appname
I think there is a little confusion regarding the django Model and the actual database table
The django model is just some python code. It is a python object that is connected to a sql table. The database backend is specified in settings.py. The database contains the actual table. The error you are encountering is indicating that the python model is not the same as the actual database table.

In Django, how to create tables from an SQL file when syncdb is run

How do I make syncdb execute SQL queries (for table creation) defined by me, rather then generating tables automatically.
I'm looking for this solution as some particular models in my app represent SQL-table-views for a legacy-database table.
So, I've created their SQL-views in my django-DB like this:
CREATE VIEW legacy_series AS SELECT * FROM legacy.series;
I have a reverse engineered model that represents the above view/legacytable. But whenever I run syncdb, I have to create all the views first by running sql scripts, otherwise syncdb simply creates tables for them (if a view is not found).
How do I make syncdb run the above mentioned SQL?
There are 2 possible approaches I know of to adapt your models to a legacy database table (without using views that is):
1) Run python manage.py inspectdb within your project. This will generate models for existing database tables, you can then continue to work with those.
2) Modify your tables with some specific settings. First of all you define the table name in your model by setting the db_table option in your meta options. Secondly you define for each field the column name to match your legacy database by setting the db_column option. Note there are other db_ options listed you possibly could use to match your legacy database.
If you really want the views approach an (ugly) workaround is possible, you can define custom sql commands per application model. This file is found in "application"/sql/"model".sql . Django will call this sql's after it created all tables. You can try to specify DROP statements for the generated tables followed by your view create statement in this file. Note that this will be a bit tricky for the tables with foreign keys as django guarantees no order of execution of these files (so stuffing all statements in one .sql will be the easiest way I think, I've never tried this before).
You could use unmanaged models for your reverse-engineered models, and initial SQL scripts for creating your views.
EDIT:
A bit more detailed answer. When you use unmanaged models, syncdb will not create your database tables for you, so you have to take care of it yourself. An important point is the table name, and how django maps Model classes to table names, I suggest you read the doc on that point.
Basically, your Series model will look like that :
class Series(models.Model):
# model fields...
...
class Meta:
managed = False
db_table = "legacy_series"
Then, you can put your SQL commands, in the yourapp/sql/series.sql file :
### yourapp/sql/series.sql
CREATE VIEW legacy_series AS SELECT * FROM legacy.series;
You can then syncdb as usual, and start using your legacy models.

Categories