I have a working django project and I want to add a new model attribute. How do I do this?
Currently I have done
class Stream(models.Model):
workingattributes = models.CharField(max_length=100)
step = models.CharField(max_length=1)
when I run 'python manage.py runserver' I receive a
DatabaseError: (1054, "Unknown column 'livestream_stream.step' in 'field list'")
I have gone into MAMP and accessed my database and added a new column 'step', but I receive the same error. Anyone have recommendations on how to add new attributes? THanks
You need to use South (or something similar) to do a Schemamigration. Read the documents to see how to do it. It's quite easy, and will be very helpful later in your project (when you have lots of data in your database). The only other option (other than using another migration tool) is to drop the database and create it again, which would lose you all of your data.
You should use South as per #Daniel Rosenthal suggestion, but the reason you are still receiving an error after creating the column is that the column you create should be named appname_modelname not just model_name so you need foo_step
Related
In my project I'm using Speedment for ORM. Of course I want my code properly tested. So I decided to create an identical copy of my default database schema which I wanted to use for unit testing. In this case the name of the original schema is "project" and the name of the copy is "test_project"
My problem is that I don't know how to properly address the other database schema.
I know that, upon establishing a connection, I can use the method withSchema("test_project") to tell speedment which schema to use.
This works just fine as long as I don't have any columns identifiers in my query.
So this works:
List <User> users = userManager.stream().collect(Collectors.toList());
whereas this doesn't:
List <User> users = userManager.stream().filter(User.UID.equal(id)).collect(Collectors.toList());
It's telling me this: Unknown column 'project.User.uid' in 'where clause
I don't really understand what's going on there. (Note: I'm quite new to Speedment).
My question is: How can I access my other schema with all its rows properly addressed to it?
This was a bug in Speedment. Changing schema withSchema("test_project") is the correct way. This will be fixed in Speedment version 3.0.23.
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.
I have been playing around with Entity Framework and MySql using the Code First approach,
When I run my code against a newly created MySql Server with no databases etc (apart from the defaults) It creates the database and tables according to the classes I have created. My issue is and I don't know if I'm doing this right is, if I make a change to my model class for example add a new property I would expect a new column to be added to that particular table. However this isn't the case instead I'm getting an error
Unknown column: 'Extent1.Email' in 'field list'
I know this is because I have made a change to the class, but I am under the impression that EF would be able to make that change automatically to the database.
I have Installed
EF 6.1.1
MySql.Data 6.9.3
MySql.Data.Entity 6.9.3
All your db initialization takes place in
Interface IDatabaseInitializer(Of In TContext As System.Data.Entity.DbContext)
You can set it in your DbContexts constructor using Entity.Database.SetInitializer() or configure it in your Web.config in <entityFramework><contexts><context><databaseInititalizer>.
To get your new columns in your existing database, you need to either do the necessary migrations (see http://msdn.microsoft.com/en-us/data/JJ591621.aspx) or you drop and recreate the database on every model change (which is what the DropCreateDatabaseIfModelChanges implementation of IDatabaseInitializer does, see http://www.adfa.se/Archive/2013/02/01/database-initializers-in-ef-code-first).
Without further information I recommend you to do the latter.
I have a Symfony 2 front end to a MySQL database. I changed my database by dropping a column on one of my tables. Within the app I have done the following to reflect this change:
removed the field from the form class
removed the field, getter & setter and annotations from the entity class
removed the field from the templates
All the pages display correctly, but when I submit after editing or creating a new record, I get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'trial_abbrev' in 'NEW'
500 Internal Server Error - PDOException
I guess I must have missed something, but I suspect it is in the depths of the Doctrine magic stuff that happens automatically.
Any suggestions much appreciated.
Not an answer but the comments to the question got confusing and somewhat disjointed. So back to basics. Run:
app/console doctrine:schema:update --dump-sql
It should say:
Nothing to update - your database is already in sync with the current entity metadata.
Please indicate what response you get and we can work from there.
I would like to implement a custom database initialization strategy so that I can:
generate the database if not exists
if model change create only new tables
if model change create only new fields without dropping the table and losing the data.
Thanks in advance
You need to implement IDatabaseInitializer interface.
Eg
public class MyInitializer : IDatabaseInitializer<MyDbContext>
{
public void InitializeDatabase(MyDbContext context)
{
//your logic here
}
}
And then set your initializer at your application startup
Database.SetInitializer<ProductCatalog>(new MyInitializer());
Here's an example
You will have to manually execute commands to alter the database.
context.ObjectContext.ExecuteStoreCommand("ALTER TABLE dbo.MyTable ADD NewColumn VARCHAR(20) NULL");
You can use a tool like SQL Compare to script changes.
There is a reason why this doesn't exist yet. It is very complex and moreover IDatabaseInitializer interface is not very prepared for such that (there is no way to make such initialization database agnostic). Your question is "too broad" to be answered to your satisfaction. With your reaction to #Eranga's correct answer you simply expect that somebody will tell you step by step how to do that but we will not - that would mean we will write the initializer for you.
What you need to do what you want?
You must have very good knowledge of SQL Server. You must know how does SQL server store information about database, tables, columns and relations = you must understand sys views and you must know how to query them to get data about current database structure.
You must have very good knowledge of EF. You must know how does EF store mapping information. You must be able to explore metadata get information about expected tables, columns and relations.
Once you have old database description and new database description you must be able to write a code which will correctly explore changes and create SQL DDL commands for changing your database. Even this look like the simplest part of the whole process this is actually the hardest one because there are many other internal rules in SQL server which cannot be violated by your commands. Sometimes you really need to drop table to make your changes and if you don't want to lose data you must first push them to temporary table and after recreating table you must push them back. Sometimes you are doing changes in constraints which can require temporarily turning constrains off, etc. There is good reason why tools which do this on SQL level (comparing two databases) are probably all commercial.
Even ADO.NET team doesn't implemented this and they will not implement it in the future. Instead they are working on something called migrations.
Edit:
That is true that ObjectContext can return you script for database creation - that is exactly what default initializers are using. But how it could help you? Are you going to parse that script to see what changed? Are you going to execute that script in another connection to use the same code as for current database to see its structure?
Yes you can create a new database, move data from the old database to a new one, delete the old one and rename a new one but that is the most stupid solution you can ever imagine and no database administrator will ever allow that. Even this solution still requires analysis of changes to create correct data transfer scripts.
Automatic upgrade is a wrong way. You should always prepare upgrade script manually with help of some tools, test it and after that execute it manually or as part of some installation script / package. You must also backup your database before you are going to do any changes.
The best way to achieve this is probably with migrations:
http://nuget.org/List/Packages/EntityFramework.SqlMigrations
Good blog posts here and here.