【发布时间】:2020-11-13 04:52:59
【问题描述】:
这是我的第一个 django 项目,我似乎仍然对外键的概念有疑问。我正在使用 mysql db,并且我定义了模型的模型(一部分/sn-p):
class Doctors(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=31)
fachrichtung = models.CharField(max_length=51)
adresse = models.CharField(max_length=24)
plz = models.CharField(max_length=6)
ort = models.CharField(max_length=9)
def __str__(self):
return self.name
class Meta:
managed = False
db_table = 'doctors'
class Leistung(models.Model):
bezeichnung = models.CharField(max_length=77)
dauer = models.PositiveIntegerField()
preis = models.FloatField()
id = models.IntegerField(primary_key=True)
artikel = models.ManyToManyField(Artikel)
class Meta:
managed = False
db_table = 'leistung'
class Behandlung(models.Model):
datum = models.DateField()
re_nr = models.CharField(max_length=12)
doctor = models.PositiveIntegerField()
istpreis = models.FloatField()
leistungs_text = models.CharField(max_length=32)
leistung = models.ForeignKey('Leistung', models.DO_NOTHING)
verrechnet_am = models.DateField()
class Meta:
managed = False
db_table = 'behandlung'
class Rechnung(models.Model):
id =models.IntegerField(primary_key=True)
doctor = models.ForeignKey('Doctors', models.DO_NOTHING)
erstellt_am = models.DateField()
class Meta:
managed=False
db_table='rechnung'
当我启动服务器并希望使用以下行生成 Rechnungen 条目时:
date = datetime.today().strftime('%Y-%m-%d')
#doctorid is a parameter passed to the view method
doc = Doctors.objects.get(id=doctorid)
rechnung = Rechnung(doctor=doc.id,erstellt_am=date)
rechnung.save()
我收到以下错误:
(1054, "Unknown column 'doctor_id' in 'field list'")
当我跑步时:
date = datetime.today().strftime('%Y-%m-%d')
#doctorid is a parameter passed to the view method
doc = Doctors.objects.get(id=doctorid)
rechnung = Rechnung(doctor=doc, erstellt_am=date)
rechnung.save()
我得到同样的错误。所以我然后尝试将医生列重命名为 Rechnungen 中的医生 ID。但后来我得到一个错误
Field 'id' expected a number but got <Doctors: AP>.
所以我从模型中删除了 str 方法,但最终出现了同样的错误.. 之后我将代码修改为:
date = datetime.today().strftime('%Y-%m-%d')
#doctorid is a parameter passed to the view method
doc = Doctors.objects.get(id=doctorid)
rechnung = Rechnung(doctor=doc.id, erstellt_am=date)
rechnung.save()
这让我回到了我的第一个错误。而且我有一种绕圈子跑的感觉。我还尝试将医生 ID 传递给Rechnung(doctor=doctorid, erstellt_am=date),但它需要医生实例。所以在删除外键之前,有没有人建议我如何解决这个问题?谢谢!
【问题讨论】:
-
您是否运行了所有迁移?
-
你可以试试
Rechnung(doctor_id=doctorid, erstellt_am=date)吗? -
@Vincent 是的 ????????我运行了所有的迁移!
-
@ruddra 我会尝试...