Добавил в модель три необязательных поля, но manage.py makemigrations создаёт миграции типа CreateTable (последних трёх полей в таблице нет, ) вместо AlterTable или AlterField:
migrations.CreateModel(
name='InviteBonus',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('total', models.DecimalField(verbose_name='\u0421\u0443\u043c\u043c\u0430 \u043f\u043b\u0430\u0442\u0435\u0436\u0430', max_digits=12, decimal_places=2)),
('use_date', models.DateField(verbose_name='\u0414\u0430\u0442\u0430 \u043f\u043b\u0430\u0442\u0435\u0436\u0430')),
('line', models.PositiveIntegerField(null=True, verbose_name='\u043b\u0438\u043d\u0438\u044f', blank=True)),
('paid', models.BooleanField(default=False, verbose_name='\u0412\u044b\u043f\u043b\u0430\u0447\u0435\u043d\u043e')),
('five_per_period', models.BooleanField(default=False, verbose_name='\u043f\u044f\u0442\u044c \u0437\u0430 \u043f\u0435\u0440\u0438\u043e\u0434')),
('comment', models.CharField(max_length=100, verbose_name='\u041a\u043e\u043c\u043c\u0435\u043d\u0442\u0430\u0440\u0438\u0439')),
('inviter', models.ForeignKey(related_name='invite_bonuses', default=None, verbose_name='\u0423\u0447\u0430\u0441\u0442\u043d\u0438\u043a', to='accounts.TreeNode')),
('newbie', models.ForeignKey(related_name='awards', verbose_name='\u043f\u0440\u0438\u0433\u043b\u0430\u0448\u0451\u043d\u043d\u044b\u0439', blank=True, to='accounts.TreeNode', null=True)),
],
options={
'db_table': 'invite_bonuses',
'verbose_name': '\u0432\u044b\u043f\u043b\u0430\u0442\u0430 \u043a\u043b\u0438\u0435\u043d\u0442\u0443 \u0437\u0430 \u043f\u0440\u0438\u0433\u043b\u0430\u0448\u0435\u043d\u0438\u0435',
'verbose_name_plural': '\u0432\u044b\u043f\u043b\u0430\u0442\u044b \u043a\u043b\u0438\u0435\u043d\u0442\u0430\u043c \u0437\u0430 \u043f\u0440\u0438\u0433\u043b\u0430\u0448\u0435\u043d\u0438\u044f',
},
bases=(models.Model,),
),
Что я делал:
— Удалял папку migrations
— Чистил таблицу django_migrations
Затем запускал
manage.py makemigrations
manage.py migrate - FAKED, потому что таблица уже есть, поэтому нужно делать добавление полей вместо создания таблицы
manage.py syncdb - Тоже ни о чём
Миграцию ни одну не сделал и не могу запустить сервер, сделать makemigrations
, migrate
вылетает эта ошибка:
django.db.utils.ProgrammingError: ОШИБКА: отношение «authorization_university» не существует
LINE 1: …le», «authorization_university».»decryption» FROM «authoriza…
^
Код ORM:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class University(models.Model):
university_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
decryption = models.CharField(max_length=200)
class Group(models.Model):
group_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
middle_name = models.CharField(max_length=150, blank=True)
class Regkey(models.Model):
key = models.IntegerField()
class Profile_student(models.Model):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
Обнаружил что когда удаляю функцию в forms.py
, спокойно все делается и запускается сервера и миграция:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Regkey, University, Group as groupdb
def func_university(): #ВОТ ЭТУ ФУНКЦИЮ
all_university = University.objects.all()
university_list = ()
university_array = []
for university_for in all_university:
university_list = (university_for.university_id, university_for.title)
university_array.append(university_list)
return university_array
class SignUpFormStudent(UserCreationForm):
first_name = forms.CharField(label='Имя')
second_name = forms.CharField(label='Фамилия')
middle_name = forms.CharField()
group = forms.CharField(label='Группа')
university = forms.ChoiceField(widget=forms.Select, choices=func_university())
email = forms.EmailField()
def clean(self):
reg_data = super(SignUpFormStudent, self).clean()
university = reg_data.get("university")
group = reg_data.get("group")
email = reg_data.get("email")
if not groupdb.objects.filter(group = group, university = university):
msg = 'Такой группы нет'
self._errors['group'] = self.error_class([msg])
del reg_data['group']
if User.objects.filter(email = email):
msg = 'Эта электронная почта занята'
self._errors['email'] = self.error_class([msg])
del reg_data['email']
return reg_data
class Meta:
model = User
fields = ('username', 'email', 'group', 'password1', 'password2')
class SignUpFormDean(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(label='Имя')
second_name = forms.CharField(label='Фамилия')
middle_name = forms.CharField()
university = forms.ChoiceField(widget=forms.Select, choices=func_university())
regkey = forms.CharField(label='Номер ключа', max_length = 16)
def clean(self):
data = super(SignUpFormDean, self).clean()
regkey_input = data.get("regkey")
if not regkey.objects.get(key = regkey_input):
msg = 'Неверный ключ или он уже был использован'
self._errors['regkey'] = self.error_class([msg])
del data['regkey']
return data
class Meta:
model = User
fields = ('username','first_name','second_name', 'email', 'regkey', 'password1', 'password2')
I have a problem (at least I think). I am new in all this, so I apologize If I ask something stupid.
I have some site, which is working normally. When I try to make migrations ( python manage.py makemigrations
), everything passed ok, I got the message of how many models new I have, etc. But, when I run after that migrate, I got the following output:
Operations to perform:
Apply all migrations: admin, auth, comments, contenttypes, news, sessions
Running migrations:
Applying comments.0003_auto_20180816_2158...Traceback (most recent call last):
File "../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: syntax error at or near "WITH ORDINALITY"
LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File ".../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File ".../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File ".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File
".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File
".../venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File ".../venv/lib/python3.6/site-
packages/django/core/management/commands/migrate.py", line 203, in handle
fake_initial=fake_initial,
File
".../venv/lib/python3.6/site-
packages/django/db/backends/base/schema.py", line 531, in _alter_field
fk_names = self._constraint_names(model, [old_field.column],
foreign_key=True)
File ".../venv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 1027, in _constraint_names
constraints = self.connection.introspection.get_constraints(cursor, model._meta.db_table)
File ".../venv/lib/python3.6/site-
packages/django/db/backends/postgresql/introspection.py", line 158, in get_constraints
""", ["public", table_name])
File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py",
line 100, in execute
return super().execute(sql, params)
File
".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/.../venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File ".../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: syntax error at or near "WITH
ORDINALITY"
LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co...
^
Anyway, if after that I try again to make migrations, got the message that I don’t have migrations. So, Django did the job, But this error is here constantly when I try to migrate, I am really wondering why. I tried to google it, but I got nothing.
Problem Description:
I have screwed up my database so I tried to redo it. I did:
1) deleted all tables via sql
2) deleted the migrations folder
So when I now do manage.py makemigrations myapp
it is creating the migration folder and the initial.py file, which looks fine. Also the __init__.py
is there. However, if i do manage.py makemigrations myapp
I always get the message “No migrations to apply.”
I looked up the database in the shell and the tables are not there.
I am using Django 1.8.
Solution – 1
Django keeps track of all the applied migrations in django_migrations
table.
So just delete all the rows in the django_migrations
table that are related to you app like:
DELETE FROM django_migrations WHERE app='your-app-name';
and then do:
python manage.py makemigrations
python manage.py migrate
Solution – 2
Django keeps track of all the applied migrations in django_migrations table.
So, you can follow this method:
-
Delete the related rows from django_migrations.
-
run python manage.py migrate.
Solution – 3
I usually ran into that issue myself. Here is the workaround I found:
Replace your database sqlite3 with this
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '<your_username>$<your_database_name>',
'USER': '<your_username>',
'PASSWORD': '<your_mysql_password>',
'HOST': '<your_mysql_hostname>',
}
}`
The fill in for can be found in the databases tab on your Pythonanywhere dashboard.
Push it to github from your Terminal and pull it down from Pythonanywhere Bash again. You may have to add this on Bash Console: pip install mysqlclient
Solution – 4
As @Anush mentioned, Django does keep track of all of the migrations in the django_migrations
table. As mentioned, you can use raw SQL to remove the migration row to reset Django’s migration history for the concerned app.
DELETE FROM django_migrations WHERE app='my-app';
If you are uncomfortable deleting rows like this, then you can use Django’s management command replacing my-app
for the name of your app.
python manage.py migrate --fake my-app zero
That command will remove the migration history rows from the database leaving you to start your migration again from scratch. You will then need to:
- Delete all of the migration files within your app’s ‘migrations’ directory but ensure that the
__init__.py
file remains. - Ensure that your app’s data models are set up as you need them
- Make the migrations again with the command
python manage.py makemigrations {your_app_name}
. This will create the0001_initial.py
file within your app’s migrations directory. - You will not be able to actually migrate the initial database migration because the database table already exists, so you will need to fake the migration with the command,
python manage.py migrate my_app --fake-initial
Solution – 5
After running into this problem on Django 3.0 I spent an entire day troubleshooting this. Sharing this so that others would not need to. Most of the times running
python manage.py makemigrations
python manage.py migrate
Should solve the problem. I followed the above step after deleting the files in migrations folder (except init.py), however I was not able to solve the problem. I found that every time you run makemigrations, a python file called 000x_xxx.py is created in the migrations folder. I looked inside the file and found that all my required changes were there but it also had other create table operations that I did not need (i.e those tables had already been created). If you run migrate with –fake or –fake-initial, the whole execution will be faked (i.e executed without actually making any change in the database).
To solve the problem I opened the generated 0000x_xxx.py file and deleted the changes I wanted to make in the database and ran «python manage.py makemigrations» again. This created a new migration file with the changes I wanted. After that I ran the following command.
python manage.py migrate --fake-initial appname
This solved the problem. Not sure if this should be this complicated.
Solution – 6
Instead of run:
python manage.py migrate
just run:
python manage.py migrate --run-syncdb
Solution – 7
If you have many problems and require a solution
Create a database backup (more than one if necessary)
My solution was to run the following query in the SQL shell
drop database database_name with (force);
This completely removes the database, be careful
It solved the error for me
Greetings
Ситуация: ты пытаешься выполнить миграции в Django. Но появляется ошибка «no changes detected» и ничего не происходит. Как исправить ошибку и провести миграцию?
Как правило, эта ошибка возникает после попытки «перекроить» базу данных. Например, ты решил, что имеющаяся база данных, ее структура требует изменений. Скажем, нужно убрать лишние поля. Быстрый и простой способ — полностью «перекомпоновать», пересоздать базу данных.
Для этого удаляется база данных и файлы миграции. Соответственно, это «костыльный» способ. Так как при этом удаляются все записи. На этапе разработки сайта или учебного проекта это возможно. На реальном сайте маловероятно — так как удаляется весь контент.
👉 При удалении файлов миграции можно допустить ошибку — удалить файл «__init__.py«. Дело в том, что для Django папка «migrations» воспринимается как приложение. И файл «__init__.py» является обязательным. Без него и возникает ошибка «no changes detected».
Проверяем, есть ли на месте этот файл. Если нет, то просто создаем его. Заметь — в названии используются двойные нижние подчеркивания. Сам файл оставляем пустым.
📢 Другие причины ошибки no changes detected
Твое приложение обязательно должно быть добавлено в INSTALLED_APPS файла «settings.py»:
Также проверяем наличие файла «__init__.py» в папке твоего приложения (где у тебя лежит файл «views.py» с представлениями, статические фалы и сама папка «migrations»).
В файле «models.py» классы должны наследоваться от «django.db.models.Model». В «models.py» должен быть соответствующий импорт, а в самом классе соответствующая запись в круглых скобках.
Проверяем, нет ли семантических ошибок в «models.py».
Также возможны ошибки при настройках Git. В частности в файле «.gitignore».