【问题标题】:Django cant figure out how to use foreign keyDjango无法弄清楚如何使用外键
【发布时间】:2021-10-13 00:07:28
【问题描述】:
class Project_types(models.Model):
    project_type = models.CharField(max_length=200)

    def __str__(self):
        return self.project_type

class Projects(models.Model):
    project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE)
    project = models.CharField(max_length=200)

    def __str__(self):
        return self.project

当我尝试运行Project_types(project_type='games').item_set.all() 我收到一条错误消息,说没有设置属性项。

【问题讨论】:

  • 你想做什么,你期望得到什么?
  • https://stackoverflow.com/questions/25890406/django-join-two-models
  • 我想要返回的只是项目类型“游戏”的空项目集
  • 记得把解决你问题的答案标记为答案!

标签: python django sqlite


【解决方案1】:
class Project_types(models.Model):
    project_type = models.CharField(max_length=200)

    def __str__(self):
        return self.project_type

class Projects(models.Model):
    project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE)
    project = models.CharField(max_length=200)

    def __str__(self):
        return self.project

首先,您的模型存在一些问题。

第一个型号名称不应该是复数形式

这里一个Projects(应该是Project)有一个project_type,一个Project_types(应该是ProjectType)有一个project。

运行您想要的查询:

Project_types.filter(project_type='games').item_set.all()

正确的查询是:

Project_types.filter(project_type='games').projects_set.all()

使用项目而不是项目,

相关管理器基于模型名称(在这种情况下,Projects 变为 projects_set)

看这里https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/

【讨论】:

    【解决方案2】:

    .item_set 属性在您通过运行创建的实例上不存在:

    Project_types(project_type='games')
    

    在我看来,您正在尝试获取 'games' 类型的所有 Projects

    为此,您必须像这样使用Projects 类的QuerySet

    Projects.objects.filter(project_types__project_type='games').all()
    

    另外,一个建议:尝试使用 singular CamelCase 命名所有模型类,这样它们会更容易理解。在您的示例中,Project_types 应该是 ProjectType,而 Projects 应该是 Project

    【讨论】:

      【解决方案3】:

      Project_types(project_type='games') 实际上并不返回任何对象。这就是你得到那个属性错误的原因。您需要添加过滤器或使用 get。如下所示:

      Project_types.objects.get(project_type='games').item_set.all()
      

      或者

      Project_types.objects.filter(project_type='games').item_set.all()
      

      【讨论】:

      • 我尝试使用这些命令,但我得到 'QuerySet' 对象没有属性 'item_set' 错误
      • 如果您试图通过过滤从此模型中获取对象,请删除 item_set。所以它将是: Project_types.objects.filter(project_type='games').all()
      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2014-12-18
      • 2013-03-05
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多