Migrations in Django 1.7 - django

I am currently involved in a project where I am using Django 1.7 development version.I want to propogate changes that I make in my models (adding a field, deleting a model, etc.) into the database schema using "makemigrations" and "migrate" commmands.I added a "age" field to one of the models in my application.
country = models.CharField(max_length=50, blank=True)
address = models.CharField(max_length=100, blank=True)
postal_code = models.IntegerField(max_length=50, blank=True)
city = models.CharField(max_length=50, blank=True)
phone_no = models.CharField(max_length=25, blank=True)
skype_name = models.CharField('Skype Username',max_length=50, blank=True)
age=models.IntegerField(max_length=25,blank=True)
When I use "makemigrations" command ,the output is like---"No changes detected".I guess that "makemigrations" is not able to figure out the changes made to the schema.Any suggestions how can I make it work??

If you are adding initial migrations to an app, you must include the app name when using the makemigrations command.
python manage.py makemigrations your_app_label

If it is the first time you are migrating that app you have to use:
manage.py makemigrations myappname
Once you do that you can do:
manage.py migrate
If you had your app in database, modified its model and its not updating the changes on makemigrations you probably havent migrated it yet.
Change your model back to its original form, run the first command (with the app name) and migrate...it will fake it. Once you do that put back the changes on your model, run makemigrations and migrate again and it should work.

I have sometimes the same problem.
I manage to populate the change in the database by following :
rm -rf your_app/migrations/*
python manage.py migrate
if it doesn't work, consider a manual drop table before, if you don't have data in it.
it worked for me with django 1.7c1

Related

Django - relation "app_name_modelname" does not exist

I've deployed my application to DigitalOcean. Everything works fine except this situation. I've added new GeneralComplaintDocument model, made migration locally, pulled from Github last version of project on DigitalOcean's server, deleted all migration files, migrated again, but still getting this error:
relation "documents_app_generalcomplaintdocument" does not exist
LINE 1: INSERT INTO "documents_app_generalcomplaintdocument"
models.py:
class Document(models.Model):
created_date = models.DateTimeField(default=timezone.now)
added_by = CurrentUserField()
class GeneralComplaintDocument(Document):
complaint_reason = models.CharField(max_length=500)
result = models.CharField(max_length=500)
def __str__(self):
return self.complaint_reason
P.S: everything works fine on local server.
I would suggest for do something like this:
first delete all migrations files in your app(documents_app)and next execute the below SQL query in your Database. Here we assume your app_name is documents_app.
delete FROM "django_migrations" WHERE "app" = 'documents_app';
then migrate ,
python manage.py makemigrations documents_app
python manage.py migrate documents_app

django datetimefield migration validation error

I haven't been able to figure out how to do what I want (not have to set datetime upon creation of object) and get around this error.
Django 1.11, Python 3.6. I am currently in the process of upgrading from Django 1.8.
Problem occurs when I run python manage.py migrate
File "C:\Dev\Python36\lib\site-packages\django\db\models\fields
\__init__.py", line 1423, in to_python
params={'value': value},
django.core.exceptions.ValidationError: ["Value '' has an invalid date
format. Must be in the format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]."]
My previous models.py (In Django 1.8)
timeToServe = models.DateTimeField(default='', null=True, blank=True,
verbose_name=get_lang(None, 'time_to_serve'))
My current models.py (In Django 1.11)
timeToServe = models.DateTimeField(default=None,
null=True, blank=True,
auto_now=False, auto_now_add=False,
verbose_name=get_lang(None, 'time_to_serve'))
My previous migration file (In Django 1.8)
('timeToServe', models.DateTimeField(default='', blank=True, verbose_name='Serveringstid', null=True)),
My current migration (0021_auto_xxxx.py) (In Django 1.11)
operations = [
migrations.AlterField(
model_name='booking',
name='timeToServe',
field=models.DateTimeField(
default=None, blank=True, null=True, verbose_name='time'),
),
There doesn't seem to be an automatic solution to this. What I did to get around this problem was to:
Check what changes in the created migration file actually would result in database changes. In my case there were some and I managed to edit the migration file to reflect those changes and remove all other changes in the migration file. I was then left with changes that Django wanted to do but would not change the database.
In my next step I uninstalled the migrations. Note the fake flag.
python manage.py migrate --fake myAppName zero
I deleted all my current migration files and there respective .pyc-file
Created new migration files
Python manage.py makemigrations
I installed the new migration file. Note the fake flag.
python manage.py migrate --fake-initial
To check status of your migrations you can run
python manage.py showmigrations

Adding columns to an existing django table with a . postgreSQL db

I've been searching around for how to do this an di think i broke my table
I tried adding
dealership = models.ForeignKey('Employee', null=True)
To the field to the models.py, since I noticed thats where my other column fields were, and now the entire table is gone.
After some more research I saw that its supposed to be added to the migrations location and then run
$ python models.py migrations
Heres the model I want to add it to
## Gate access log - receives from RPi via API
##
class Eventlog(models.Model):
ENTRY = 1
EXIT = 2
EVENT_CHOICES = (
(ENTRY, 'Entry'),
(EXIT, 'Exit'),
)
event = models.PositiveSmallIntegerField(choices=EVENT_CHOICES)
employee = models.ForeignKey('Employee', null=True)
timestamp = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True, help_text="Whether the employee was granted access")
def __unicode__(self):
return self.timestamp
def __str__(self):
return self.timestamp
and as the comment suggests, it pulls the from a raspberry pi through an api
My question is how do I properly add the column, the db already has the information for the column data I can't imagine it's that difficult to simply pull that info and how do I get my table back? The table seems to have vanished after I added to the models.py manually and when I tried undoing it just never came back.
You need to run two commands:
python manage.py makemigrations
then
python manage.py migrate
To add columns in postgresql db solution as below:
pip install django-extensions
and add this in the install app of settings.py
INSTALLED_APPS = [
'django_extensions'
]
Now, run migrations for your installed apps
python manage.py makemigrations your_app_name
python manage.py migrtate your_app_name
Done! See Your Database...

NOT NULL constraint failed when running `migrate`

I changed my models.py file and when running migrate I get this error. The property is a OneToOneField(). I have tried adding null=True but that doesn't seem to fix it. It is also weird that even when I comment out the property and run makemigrations followed by migrate, I still get that exact same error. Is there a way to fix this? My model looks like this:
class Estimator(Employee):
avg_estimate = models.IntegerField()
class Job(models.Model):
created = models.DateTimeField(auto_now_add=True)
estimator = models.OneToOneField(Estimator, null=True)
address = models.CharField(max_length=100)
completed = models.BooleanField(default=False)
My guess is that you have created a migration without null=True, that won't migrate, then you created a second migration with null=True.
Running "migrate" will run both migrations in order, so the first one will fail again.
Assuming this is the case, then
1: delete the two most recent files in your migrations folder. (Open them first to confirm that they are creating the migrations as I described before deleting them).
2: run makemigrations again, with null=True in your models.py
This should create the equivalent of the second migration file, without the failing intermediate migration.

django 1.7 makemigrations on existed table

I want to use Django 1.7 for a new project.
and I already have database with many records.
In many Django tutorials,
it demo how to use migration system from a fresh new project.
In my case, use django-admin startapp todo
and will use a existed table named notesnote.
I use inspectdb to dump notesnote class and write it into todo/models.py
class NotesNote(models.Model):
title = models.CharField(max_length=100)
text = models.TextField()
pub_date = models.DateTimeField()
authors = models.CharField(max_length=10)
and then
python manage.py makemigrations todo
to generate todo/migrations/0001_initial.py
then
python manage.py migrate --fake todo
do a fake migrate(cause the table already existed).
Then, If I want to amend the table's field, say add a "category" field
category = models.CharField(max_length=30)
Then generate the 0002 migration diff by:
python manage.py makemigrations todo
However, when I do the migrate by
python manage.py migrate todo
I got error as below:
django.db.utils.OperationalError: no such table: todo_notesnote
Seems it add the app's name in front of the existed table.
Which steps should I do to make a usable migrations for existed table?
The documentation about integrating Django with a legacy database contains some useful advices for your use case: in particular you should add a db_table = 'notesnote' option to the inner Meta class of your model.