[Django]-Django: Filtering query with foreign key not working

4👍

Your status is a model by itself, so you should do this:

incident_list = Incident.objects.filter(status__status='open').order_by('-incident_date_reported')

Also I think your design doesn’t make much sense. If you only need a string as status on Incident, you don’t need the model Status, just take the status field to Incident, and your old query would work.

Edit:
If you want to restrict your selections to be a certain set, you should consider using choices: https://docs.djangoproject.com/en/1.8/ref/models/fields/#choices

Then your model becomes:

class Incident(models.Model):
    STATUS_CHOICES = (
        ('open',   'Open'),
        ('closed', 'Closed'),
        # some other statuses go here
    )
    incident_date_reported = models.DateField('Date Reported',
                                              default=timezone.now)
    status = models.CharField(max_length=20,
                              choices=STATUS_CHOICES,
                              default='open')

Leave a comment