【问题标题】:Django filtering on foreign keyDjango过滤外键
【发布时间】:2017-03-04 14:21:27
【问题描述】:

您好,感谢您的阅读。

以下是我的数据模型的相关部分。我想在我的论坛中提取给定部分的所有线程。但我正在努力让它发挥作用。这是数据模型:

class ForumSections(models.Model):
    heading = models.CharField(max_length=200)
    icon = models.CharField(max_length=50)
    hits = models.IntegerField(default=0)

    def __str__(self):
        return "Section: %s" % (self.heading)

class ForumThread(models.Model):
    heading = models.ForeignKey(ForumSections, on_delete=models.CASCADE)
    threadTitle = models.CharField(max_length=200)
    threadStatus = models.BooleanField(default=True)

    def __str__(self):
        return "Thread: %s Under Section: %s" % (self.threadTitle, self.heading

所以我想我想做这样的事情:

ForumThread.objects.filter(ForumSections__heading=heading)

但是这会返回错误:

django.core.exceptions.FieldError: Cannot resolve keyword 'ForumSections' into field

非常感谢您的帮助 - 我被困在这里了。

谢谢! 汤米

【问题讨论】:

  • 你被困在这里,但问题到底是什么?

标签: django filtering


【解决方案1】:

这应该是

ForumThread.objects.filter(heading__heading=heading)

因为 heading 是模型 ForumThread 中的字段。

【讨论】:

  • 嘿,谢谢 - 这行得通。出于某种原因,我认为我必须在反向外键中引用该表。
猜你喜欢
  • 2020-09-07
  • 2012-01-23
  • 2018-01-05
  • 2013-09-05
  • 2016-07-12
  • 2013-09-04
  • 2021-01-26
  • 2020-12-08
  • 1970-01-01
相关资源
最近更新 更多