Django模型未定义



我一直在研究一些视图,现在使用一个模型已经有一个星期了,直到现在还没有问题:我没有改变任何东西,只是向模型添加了一个新字段,现在myModel.objects.create()给了我一个名称未定义错误。我已经导入了模型,正如我所说,我已经为此工作了一个星期,并且我使用完全相同的代码创建了几个模型。

模型:

class Prescription(models.Model):
prescription_id = models.CharField(max_length=26, default=prescription_id, editable=False, unique=True) # THIS IS THE FIELD I ADDED BEFORE HAVING THIS ERROR
appointment = models.ForeignKey('booking.Appointment', on_delete=models.SET_NULL, null=True, blank=True)
doctor = models.ForeignKey('core.Doctor', on_delete=models.CASCADE)
patient = models.ForeignKey('core.Patient', on_delete=models.CASCADE)
overriden_date = models.DateField(null=True, blank=True)
control = models.BooleanField(default=False)
control_date = models.DateField(null=True, blank=True)
send_email = models.BooleanField(default=False)
posted = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Ordonnance"
verbose_name_plural = "Ordonnances"
def __str__(self):
return str(self.id)

class PrescriptionElement(models.Model):
prescription = models.ForeignKey('Prescription', on_delete=models.CASCADE)
drug = models.ForeignKey(Drug, on_delete=models.CASCADE, null=True)
custom = models.CharField("Elément", max_length=25, null=True, blank=True)
dosage = models.CharField(max_length=45, null=True, blank=True)
posologie = models.CharField(max_length=256, null=True, blank=True)
duration = models.CharField("Durée", max_length=15, null=True, blank=True)

视图:

PrescriptionElement.objects.create(prescription=prescription, drug=listemedicament, custom=medicament, dosage=dosage, posologie=posologie, duration=duree)
错误:

name 'PrescriptionElement' is not defined

我通过删除多个文件之间的任何循环关系修复了这个问题。循环导入是导致这种情况的一个问题。prescription_id默认值是在一个名为utils.py的文件中定义的,在utils.py中有一些函数从models.py文件中继承模型。删除此循环关系可修复此问题。

另外,使用这种格式来定义foreignkey ('booking.Appointment')是避免导入的更好选择。

最新更新