Tom Paulick
Tom Paulick

Reputation: 63

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

Upvotes: 0

Views: 47

Answers (1)

Mohammad Mustaqeem
Mohammad Mustaqeem

Reputation: 1084

This should be

ForumThread.objects.filter(heading__heading=heading)

as heading is the field in the model ForumThread.

Upvotes: 1

Related Questions