我正在尝试建立一个小项目——一个电子学习项目。我正试着把一些练习绑定到它的课程id上
我读过django文档,不知道应该使用OneToOne字段还是外键
我用外键尝试了这个想法,因为我觉得这是正确的答案。 课程-models.py(Lectie=lesson)
from django.db import models
# Create your models here.
class Lectie(models.Model):
YTLink = models.CharField(max_length = 100)
PDFLink = models.CharField(max_length = 100)
练习-models.py(intrebare=问题,variante=选项,variantaCorecta=正确答案)
from django.db import models
from django.contrib.postgres.fields import ArrayField
from lectii.models import Lectie
# Create your models here.
class Exercises(models.Model):
idLectie = models.ForeignKey(Lectie, on_delete=models.DO_NOTHING)
intrebare = models.CharField(max_length = 300)
variante = ArrayField(models.CharField(max_length=300), null=True)
variantaCorecta = models.IntegerField()
def __str__(self):
return self.intrebare
我得到了这个错误:
You are trying to add a non-nullable field 'idLectie' to exercises without a default; we can't do that (the database needs something to populate existing rows).
我只在后端添加这些问题,用户不会添加这些问题,我得到了这个答案。Django不知道将该练习绑定到哪个ID
那么,我的模型应该是什么样子的,这样我就可以把这个练习和它的课程结合起来?这样就可以添加一个空格=True,然后更改ID吗?或者我应该换成一对一的关系?谢谢 谢谢
如果一个课程有多个课程,那么
ForeignKey
是合适的。OneToOne
字段只是带有unique=True
约束的ForeignKey
,这意味着两个对象之间只允许存在一个关系至于你的错误,你有两个选择:
1)设置一个
default=...
属性,这在本例中没有意义,因为似乎每个课程都不应该有一个“默认”练习2)将ForeignKey设置为
blank=True, null=True
,然后手动设置每个Lesson
。您始终可以删除blank=True, null=True
,然后再次迁移您需要提供一个默认值:
还要确保在“其他”的表中有一行
相关问题 更多 >
编程相关推荐