简体   繁体   English

Django对外键进行过滤

[英]Django filtering on foreign key

Hi and thanks for reading. 嗨,谢谢您的阅读。

Below is the relevant piece of my Data Model. 以下是我的数据模型的相关部分。 I want to pull all the threads for a given section in my forum. 我想提取论坛中给定部分的所有主题。 but I'm struggling to get this to work. 但是我正在努力使它起作用。 Here's the data model: 这是数据模型:

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

so I'm thinking I want to do something like: 所以我想我想做些类似的事情:

ForumThread.objects.filter(ForumSections__heading=heading)

However this returns an error : 但是,这将返回错误:

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

Really appreciate your help - I'm stuck here. 非常感谢您的帮助-我被困在这里。

Thanks! 谢谢! Tommy 汤米

This should be 这应该是

ForumThread.objects.filter(heading__heading=heading)

as heading is the field in the model ForumThread . 标题ForumThread模型中的字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM