Working with primary key field in legacy database using Django - mysql

I have to create a simple CRUD panel for an active MySQL database. When I try to migrate my application I receive the following error:
AssertionError: A model can't have more than one Autofield
I've read the following in The Django Book, Chapter 18:
Each generated model has an attribute for every field, including id
primary key fields. However, recall that Django automatically adds an
id primary key field if a model doesn’t have a primary key. Thus,
you’ll want to remove any lines that look like this:
id = models.IntegerField(primary_key=True) Not only are these lines
redundant, but also they can cause problems if your application will
be adding new records to these tables.
I have the same scenario with this field:
id_call = models.BigIntegerField(primary_key=True)
However, if I follow the above suggestion and remove this line, the original application (not the django application) using this table may not work properly because it could be calling data from this table using this id_call field.
How can I resolve this situation?

For me, by changing models.AutoField(unique=True) to models.AutoField(primary_key=True), while working with a Wordpress database.
I had about 4 of them in generated models.py by python manage.py --database='olddb' inspectdb > models.py. Here i used one more db, say olddb, if you use default db then you can remove --database='olddb'.
I tried running python manage.py runserver. So i fixed each line by things mentioned above.
Reference:-
https://docs.djangoproject.com/en/1.8/topics/db/models/#automatic-primary-key-fields
https://docs.djangoproject.com/en/1.8/topics/db/multi-db/#

Related

Migrate existing database fields.E340 error on run

Hey everyone I'm fairly new to Python Anywhere, I'm running a django app on python 3.7, I've manually added the tables and fields I need via SSH in MySQL Workbench and ran [migrate.py inpectdb > /app/models.py] then makemigrations then when I run Migrate I get this:
ERRORS: auth.Group.permissions: (fields.E340) The field's intermediary table 'auth_group_permissions' clashes with the table name of 'app.AuthGroupPermissions'. auth.User.groups: (fields.E340) The field's intermediary table 'auth_user_groups' clashes with the table name of 'app.AuthUserGroups'. auth.User.user_permissions: (fields.E340) The field's intermediary table 'auth_user_user_permissions' clashes with the table name of 'app.AuthUserUserPermissions'.
If I remove the auth tables from the models.py and try to migrate I get:
File "/usr/lib/python3.7/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes')
From what I've read it is conflicting with the settings.py [INSTALLED_APPS] but I'm not sure where to go from here to get the migration to work properly.
The extra tables that you noticed were created by Django because you have the app that creates those tables enabled in your INSTALLED_APPS. From the table names involved, I'm guessing it's django.contrib.auth that's adding them. There are probably other tables that are being created that way, but they are just not clashing with the tables you've already created.
The second error you're getting is because you have tried to create a key on a column (or columns) that is too big to be a key. That may still be as a result of the auth_ tables clashing. For instance, the Django model may be specifying a key on the id of a table, expecting it to be an integer column, but your database has a large string column for id instead.
I suspect that you may continue to have issues as long as you try to get the Django database and your database to be in the same database. Django does, however, support multiple databases so you could put your legacy database in one database and have your Django database in another. That way, they have no way on stepping on each other.

A model in DJANGO with 4 fields, two of them give error:"add a non-nullable field....". my question is why other two fields dont give error

here is the full error:
You are trying to add a non-nullable field 'summary' to product without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py
My first question is why not all fields give me the error even tough they are identical fields?
Second question how can I fix this without typing this: TextField(default="any string") ?
Third question, I am using mysql,If I was using a different db would I get the same error?
models.py
from django.db import models
class Product(models.Model):
title=models.TextField()
description=models.TextField()
price=models.TextField()
summary=models.TextField()
admin.py
from django.contrib import admin
from .models import Product
admin.site.register(Product)
command
python manage.py makemigrations
my admin page has "Product" tab. When I create a product in admin window, i have only two fields. description and price.
From the error, I think there are existing rows in your db. When you want to add new columns on the existing table and you did not say the column is nullable by
summary=models.TextField(null=True)
So you have to set default value either during migration or you can define the default value in your model. You can choose Option 1 during makemigrations and set 'Something' or None as default.
There is an answer in the error: the database needs something to populate existing rows.
It means that when you initially added first when you created a model and a first migration for it there were no any rows of instances. But now you are trying to add another field separately to existing database and Django asks you to specify the default value for those existing rows.
There is a way to solve that issue:
Delete migrations where you crate that table and generate a new migration where all those fields will be credited simultaneously.

Deleting a table from MySQL database in Django manually

During my experimentation with my blog app (blogapp) in Django, I created two models (Category and Language), connected them to another model (Post) using following connections:
category = models.ManyToManyField(Category)
language = models.ForeignKey(Language)
Then it gave an error like THIS due to the lack of default value. Tried to roll that back by using an amalgam of THIS and THIS. Then I tried to add a default value using THIS. I've got an error "django.db.utils.OperationalError 1050, Table XXX already exists", then I tried THIS. Tried to revert back migrations by deleting the created migrations from the migrations folder manually. At some point I got django (1054, "Unknown column in 'field list") error.
Finally I decided to revert back to my original starting place. When I connect to my MySQL database using python manage.py dbshell, I realized that my MySQL server still have two tables that should have been deleted, blogapp_category and blogapp_language. Server is working properly but I keep getting "Table XXX already exists" error when I try to add those models.
Dropping tables from MySQL seems to be the only option at the moment.
When I run
mysql> SHOW COLUMNS FROM blogapp_post;
I did not see any reference to language or category, i.e. no columns named language_id or category_id. I have two questions at the moment:
Is it safe to delete tables manually using:
DROP TABLE blogapp_language;
DROP TABLE blogapp_category;
Will there be any negative effects?
Is there a way to freeze database like git so that when I revert to the old database, such tables added to the database by django migrations automatically dropped??
Delete respective entry from table django_migrations.
Delete migration folder from your app.
Delete table created by the app.
Now do makemigrations and migrate.
You can revert back using git but there will be errors and data correction requirements.

ASP.NET Azure MySQL code first migrations: Table 'xxx' already exists

I have this frustrating problem when trying to enable code migrations to create DB schema on azure MySql DB i got the:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
specified to my data context and also
var configuration = new App.Migrations.Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();
but a simple Table that contains only ID property and a String doesnt seem to work on Azure, it says
Table 'xxx' already exists, and when it doesnt it gives another error saying
Specified key was too long; max key length is 767 bytes
whats wrong with the MySQL and Code First schema generation?
thanks
Issue is likely...
Your Entity Code
Your Seed Code
Table probably does already exist
I would recommend opening the Visual Studio 2015 SQL Server Object explorer and running a few queries on the tables in question or just see if those tables exist and what data is in them.
I also do not like code first migrations, for these sorts of reasons. I would recommend following this tutorial series.
https://channel9.msdn.com/Blogs/Have-you-tried-turning-it-off-and-on-again/Creating-a-Database-Project-for-Artificial-Intelligence
https://channel9.msdn.com/Blogs/Have-you-tried-turning-it-off-and-on-again/Deploying-Database-Projects-to-SQL-Azure
https://channel9.msdn.com/Blogs/raw-tech/AI-Part-3-Entity-Framework-and-Unit-Tests

Indexes in Django after running syncdb

Is it there a way to know the current status of mySQL tables in Django after creation through syncdb or do I need to use dbshell?
Another quick question: Suppose I add an index manually after running syncdb, do I have to add index_db to the corresponding field in the model?
Regards
you don't have to. index_db only tells django to add an index when creating the table. adding it subsequently has no effect (though you may want to add it anyway to indicate the presence of and index). if you are using south (you should be) then adding index_db will add index creation to your next migration.