python django.db.utils.OperationalError:无此列:users_classroom.class_code尝试迁移时

aiqt4smr  于 2023-03-28  发布在  Python
关注(0)|答案(1)|浏览(116)

这是我的第一个Django项目,我试图将class_code属性添加到Classroom中,class_code是一个随机的6个字符串,我计划使用它来允许用户使用它加入教室。我试图使用以下帖子中的代码使其随机:https://stackoverflow.com/a/67546412/20015529并遵循此django文档:https://docs.djangoproject.com/en/4.1/howto/writing-migrations/#migrations-that-add-unique-fields。由于uuid的长度,我修改了指令以使用随机字符串而不是uuid。当尝试迁移时,我收到以下错误:“django.db.utils.OperationalError:无此列:users_classroom.class_code”. Screenshot of full error message
这是我的Django文件。我的项目名是Project,应用程序名是users。
Forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile, Classroom
from home.models import Announcements
class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']
         
        def clean_email(self):
            email = self.cleaned_data['email']
        #   if User.objects.filter(email=email).exists():
                
            #   raise forms.ValidationError('That email is in use. Please Log in or use a different Email')
            return email

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email']

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']

class ClassJoinForm(forms.ModelForm):
    class Meta:
        model = Classroom
        fields = ['classroom']

Models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image
import random

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)

        img = Image.open(self.image.path).convert('RGB')

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

class Classroom(models.Model):
    classroom = models.OneToOneField(User, on_delete=models.CASCADE)

    def create_new_class_code():
        not_unique = True
        while not_unique:
            unique_ref = random.randint(1000000000, 9999999999)
            if not Classroom.objects.filter(class_code=unique_ref):
                not_unique = False
        return str(unique_ref)
    class_code = models.CharField(
            max_length = 6,
            blank=True,
            editable=False,
            unique=True,
            default="AAAAAA"
        )

    def __str__(self):
        return f'{self.classroom.username} Classroom'

    def save(self, *args, **kwargs):
        super(Classroom, self).save(*args, **kwargs)

0003_classroom_class_code.py(迁移文件)

# Generated by Django 4.1.7 on 2023-03-27 00:29

from django.db import migrations, models
from django.contrib.auth.models import User
import users.models

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0002_classroom'),
    ]

    operations = [
        migrations.AddField(
            model_name='classroom',
            name='class_code',
            field=models.CharField(blank=True, default=users.models.Classroom.create_new_class_code, editable=False, max_length=6, null=True),
        ),
    ]

0004_自动化_20230326_1931.py

# Generated by Django 4.1.7 on 2023-03-27 00:31

from django.db import migrations
from django.contrib.auth.models import User

def create_new_class_code():
        not_unique = True
        while not_unique:
            unique_ref = random.randint(1000000000, 9999999999)
            if not Transaction.objects.filter(Referrence_Number=unique_ref):
                not_unique = False
        return str(unique_ref)

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0003_classroom_class_code'),
    ]

    operations = [
        migrations.RunPython(create_new_class_code)
    ]

0005_auto_20230326_1931.py

# Generated by Django 4.1.7 on 2023-03-27 00:31

from django.db import migrations, models
from django.contrib.auth.models import User
from users.models import Classroom
import uuid

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0004_auto_20230326_1931'),
    ]

    operations = [
        migrations.AlterField(
            model_name='classroom',
            name='class_code',
            field=models.CharField(blank=True, default=Classroom.create_new_class_code, editable=False, max_length=6, unique=True),
        )
    ]

0006_alter_classroom_class_code.py

# Generated by Django 4.1.7 on 2023-03-27 02:26

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('users', '0005_auto_20230326_1931'),
    ]

    operations = [
        migrations.AlterField(
            model_name='classroom',
            name='class_code',
            field=models.CharField(blank=True, default='AAAAAA', editable=False, max_length=6, unique=True),
        ),
    ]

我试过通过sqlflush和flush命令清除数据库,但似乎没有任何作用,所以我恢复了数据库文件。

fruv7luv

fruv7luv1#

在0003_classroom_class_code.py中,当添加新字段时,django会尝试将默认值添加到数据库中所有现有的示例。问题是,您的默认函数使用filter中的class_code字段,该字段尚未添加(if not Classroom.objects.filter(class_code=unique_ref):
我的建议是:
1.通过以下命令迁移到稳定迁移:python manage.py migrate users 0002
1.删除从0003开始的所有迁移
1.使用新的class_code default执行makemigrations(将其设置为AAAAAA,应该可以工作)
optional:3.1)在makemigrations之后向新的迁移文件添加RunPython代码,它将获取Classroom的所有对象并将class_code设置为create_new_class_code(就像你在0004中所做的那样,但是将其添加到操作列表中的AddField之后)

  1. migrate

相关问题