I'm using the contribute_to_class
method but I don't know how to create the field in the database with new migrations.
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- TypeError: 'BaseQuery' object is not calla
- Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
- Django is sooo slow? errno 32 broken pipe? dcramer
- Django: Replacement for the default ManyToMany Wid
- Upgrading transaction.commit_manually() to Django
You can create like this:
See "Django Model Field Injection" for more information.
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with
./manage.py makemigrations
and then run./manage.py migrate
and the new field will be added to your DB.To avoid dealing with errors for your existing models however, you can use the
--fake
:Initialize migrations for your existing models:
Fake migrations for existing models:
Add the new field to myapp.models:
Run makemigrations again (this will add a new migration file in migrations folder that add the newfield to db):
Run migrate again:
To be able to do that and have the migration file located in the application where I actually add the field as opposed to having the migration located inside the application to which the model belongs, I had to write my own Migration base class.
If you use
contribute_to_class
inside the same application as the original model, @nima's answer works perfectly, although I don't see the point of usingcontribute_to_class
then.Here is the code. It is Django's original code adapted to migrate a model from
self.migrated_app
instead ofself.app_label
:With this new Migration class located in
base.utils
a hand-written migration would look like this. You can also let Django write the migration for you inside the "wrong" application, move the file and update it to use the custom Migration class:Custom migration class for Django 1.8