gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:25:27 25 4
gpt4 key购买 nike

我正在使用 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: name 'questions' is not defined

最佳答案

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

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

以下是相关文档:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey

关于python - 如何拥有一个包含四个表的 Django 关系数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com