开发者社区> 问答> 正文

如何拥有一个包含四个表的Django关系数据库?

一码平川MACHEL 2019-01-22 13:21:32 389

我正在使用Django创建一个网站,并且数据库存在问题!我有四个表(主题,问题,答案和图像)。这些表中的每一个都有一个id列,我想将这四个表连接在一起。

我试过使用ForeignKey()但是没有用。我收到一条错误消息。我不知道我是否可以ManyToManyField()在这种情况下使用,因为我只想连接一列。

这是代码:

from django.db import models

# Create your models here.
class topics(models.Model):

topic_id = models.AutoField(primary_key=True)
topic_level = models.BooleanField()
topic_name = models.TextField()

class questions(models.Model):

question_id = models.AutoField(primary_key=True)
description = models.TextField()
questions_type = models.BooleanField()

class answers(models.Model):

answer_id = models.AutoField(primary_key=True)
description = models.TextField()

class images (models.Model):

image_id = models.AutoField(primary_key=True)
image_blob = models.BinaryField()

这是代码ForeignKey():

from django.db import models

# Create your models here.
class topics(models.Model):

topic_id = models.AutoField(primary_key=True)
topic_level = models.BooleanField()
topic_name = models.TextField()
topic_question = models.ForeignKey(questions, on_delete=CASCADE)
topic_answer = models.ForeignKey(answers, on_delete=CASCADE)
topic_image = models.ForeignKey(images, on_delete=CASCADE)

class questions(models.Model):

question_id = models.AutoField(primary_key=True)
description = models.TextField()
questions_type = models.BooleanField()
question_topic = models.ForeignKey(topics, on_delete=CASCADE)
question_answer = models.ForeignKey(answers, on_delete=CASCADE)
question_image = models.ForeignKey(images, on_delete=CASCADE)

class answers(models.Model):

answer_id = models.AutoField(primary_key=True)
description = models.TextField()
answer_topic = models.ForeignKey(topics, on_delete=CASCADE)
answer_question = models.ForeignKey(questions, on_delete=CASCADE)
answer_image = models.ForeignKey(images, on_delete=CASCADE)

class images (models.Model):

image_id = models.AutoField(primary_key=True)
image_blob = models.BinaryField()
image_topic = models.ForeignKey(topics, on_delete=CASCADE)
image_question = models.ForeignKey(questions, on_delete=CASCADE)
image_answer= models.ForeignKey(answers, on_delete=CASCADE)

这是我收到的错误消息:

topic_question = models.ForeignKey(questions,on_delete = CASCADE)NameError:名称'问题'未定义

数据库 Python
分享到
取消 提交回答
全部回答(1)
  • 一码平川MACHEL
    2019-07-17 23:26:15

    在您尝试使用question类名来指示相关模型时,未定义此类,因为错误状态。当您引用稍后在代码中定义的模型时,必须将名称括在"":

    topic_question = models.ForeignKey("questions", on_delete=CASCADE)

    0 0
+ 订阅

分享数据库前沿,解构实战干货,推动数据库技术变革

推荐文章
相似问题