Django模型编写报错求助:依据ER图实现模型提交失败
Django模型代码错误排查及修复方案
问题背景
学习Django时根据ER图编写模型,提交后网站报错,规则说明:
- 粗体字段为ForeignKey或PrimaryKey
- 无需编写灰色字段
- 斜体字段需继承
以下是代码中存在的问题及修复:
1. accounts/models.py 错误点
问题:重复定义AbstractUser已包含的字段,且参数无效
User类继承AbstractUser后,无需重新定义is_active、is_staff、is_superuser——这些字段是AbstractUser自带的;同时models.BooleanField的第一个参数不应传入AbstractUser,这属于无效参数。
修复后的代码:
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): # 仅添加AbstractUser没有的自定义字段即可,无需重复声明继承字段 pass
2. charities/models.py 错误点
问题1:相对导入路径易引发错误
使用from ..accounts.models import User这种相对导入,在Django应用中可能导致导入路径异常,建议改用绝对导入或字符串引用。
问题2:experience字段类型与选项值不匹配
experience被定义为SmallIntegerField,但EXP_CHOICES的键是字符串类型,默认值也是字符串'0',类型不匹配会触发数据库存储错误。
修复后的代码:
from django.db import models from accounts.models import User # 绝对导入,或使用字符串引用'accounts.User' class Benefactor(models.Model): EXP_CHOICES = ( (0, 'Beginner'), (1, 'Average'), (2, 'Expert') ) user = models.OneToOneField(User, on_delete=models.CASCADE) # 字段类型为整数,选项键和默认值统一用整数类型 experience = models.SmallIntegerField(null=True, blank=True, choices=EXP_CHOICES, default=0) free_time_per_week = models.PositiveSmallIntegerField(null=True, blank=True) class Charity(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True, blank=True) reg_number = models.CharField(max_length=10, null=True, blank=True) class Task(models.Model): STATE_CHOICES = ( ('P', 'Pending'), ('W', 'Waiting'), ('A', 'Assigned'), ('D', 'Done'), ) assigned_benefactor = models.ForeignKey(Benefactor, null=True, on_delete=models.SET_NULL) charity = models.ForeignKey(Charity, on_delete=models.CASCADE) state = models.CharField(max_length=1, choices=STATE_CHOICES, default='P') title = models.CharField(max_length=60)
额外注意事项
- 确保
settings.py的INSTALLED_APPS中已添加accounts和charities应用 - 修复后执行迁移命令:
python manage.py makemigrations→python manage.py migrate
内容的提问来源于stack exchange,提问作者Shadmehr
相关产品推荐
相关产品推荐

