user1807271
user1807271

Reputation: 1006

Django: Filtering query with foreign key not working

I want to filter a query with a foreign key, but it doesn't seem to want to recognize it. status can either be 'open' or 'closed'.

models.py

class Status(models.Model):
    status = models.CharField(primary_key=True, max_length=100)

class Incident(models.Model):
    incident_date_reported = models.DateField('Date Reported', default=timezone.now)
    status = models.ForeignKey(Status, default="open")

views.py

def index(request):

    template = "index.html"                 
    form = IncidentSearchForm(request.GET)

    if request.method == 'GET':

        form = IncidentSearchForm()

        ############## MY QUERY THAT DOESN'T LIKE THE FOREIGN KEY #############
        incident_list = Incident.objects.filter(status = 'open').order_by('-incident_date_reported')
        #######################################################################

       context = {  "form": form,
                    "incident_list": incident_list
                  }

        return render(request, template, context)

Upvotes: 3

Views: 1420

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

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')

Upvotes: 4

Related Questions