Django automatically create primary keys for existing database tables - python

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!

Related

django table has no column named Exception

Git Repository
Request to guide me on what to do.
I work on an e-commerce website with the help of Django. and I'm a beginner in Django
The following image provides a table of my database. It helps to add a product
Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.
An error occurred while migrating
Request to guide me on what to do.
After first migrations,if you add any field that can not be null you must provide a default value. Your desc field is not nullable, so you must add default='some_value' inside your desc field.
Do you have the table ready and set up? Because the error says, that there is a table named shop_product, but it does not have a column named product_name.
So the structure of your table would get us closer to the solution of your problem.
Edit:
I have just seen, that you supplied your Git repo. I looked at the database and what I wrote above holds true. Your shop_product table has no columns. I did not look through your code to see if it would be set up automatically, but I suppose you were supposed to create the columns by hand, right?
Take a look at here (Django Migrations Workflow)
I've seen your migrations folder on your Github repo and there was no sign of any of the fields you mentioned.
Every time you add fields to your models, you need to run following commands in terminal
python manage.py makemigrations <app name>
python manage.py migrate
These commands are going to modify your tables.
Please markdown your question instead of putting a picture from your code.
Check this out: How do I ask a good question?
EDIT:
In your Product model, there is a field named desc. You need to set a default value for it; Otherwise, you need to update the records in your database manually.
desc = models.CharField(max_length=300, default='')
After you do that, this error will happen to the pub_date field too. So, if your current Product objects in your database are not important, you can simply delete the database file db.sqlite3 and delete your migrations file from this address shop/migrations/0001_initial.py and try the migration commands again.

sqlite configuring with django

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

Django incorrectly expecting id column

I'm working with an existing SQL database in Django. These tables for some reason were never given primary keys so I'm just going through and assigning them ones. In one of these models, I changed an existing unique index to a primary index using primary_key = True. I then ran ./manage.py makemigrations (app_name); ./manage.py migrate. I came across this error: (1091, "Can't DROP 'id'; check that column/key exists"). It seems as though Django assumed that there was an id field for the model when there wasn't because I was able to use phpMyAdmin to make an id field, and when I re-ran the migration it succeeded. While I was able to fix my problem I doubt that this is the best way to go about it. What is the correct way to deal with this problem?
You could fake a migration only including removing the "id" field using the --fake option when migrating, so django thinks that it had deleted the id field when really it never existed.

members_data.dob may not be NULL in Django

Using Django 1.4 in my app I defined a model called Member and another called Data.Every member has basic like ID and it is related to a Data object that contains additional variables describing the "member".
I had initially created the member model without specifying that the dob variable could be NULL. I have since then changed this to allow for blank or null but I was still getting the members_data.dob may not be NULL error.
I thought it was because I needed to run a syncdb command, which I did, however this did not fix the problem.
dob = models.CharField(max_length=200, blank=True, null=True)
Any ideas? Thanks
ps. If you want to get an overall picture of what I am trying to implement please refer to: Can I use JSON data to add new objects in Django?
Thanks so much.
The syncdb command only creates tables if they do not exist. It does not handle migrations for you. You have a few options:
If there is no important data in the table, drop the table and run syncdb again to recreate it.
Update the column to allow null in a db shell. The correct command depends on which database you are using.
Use a migration tool, like South.
To drop the table in sqlite:
Open a dbshell
./manage.py dbshell
Drop the table
drop table <tablename>

Django: Change models without clearing all data?

I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data?
I tried changing the field and running python manage.py syncdb. There was no output from this command.
Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors as Django sought to display fields that didn't exist in the db.
I am using SQLite.
I am able to delete the db file, then re-run python manage.py syncdb, but that is kind of a pain. Is there a better way to do it?
Django does not ever alter an existing database column. Syncdb will create tables, but it does not do 'migrations' as found in Rails, for instance. If you need something like that, check out Django South.
See the docs for syndb:
Syncdb will not alter existing tables
syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.
If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.
You have to change the column names in your DB manually through whatever administration tools sqlite provides. I've done this with MySQL, for instance, and since MySQL lets you change column names without affecting your data, it's no problem.
Of course there is.
Check out South
You'll have to manually update the database schema/layout, if you're only talking about adding/removing columns.
If you're attempting to rename a column, you'll have to find another way.
You can use the python manage.py sql [app name] (http://docs.djangoproject.com/en/dev/ref/django-admin/#sql-appname-appname) command to see what the new SQL should look like, to see what columns, of what type/specification Django would have you add, and then manually run corresponding ALTER TABLE commands.
There are some apps/projects that enable easier model/DB management, but Django doesn't support this out of the box, on purpose/by design.

Categories