Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting database values using get_object_or_404

Tags:

django

I am using get_object_or_404 to try to get a list of values from my database. I'm trying to filter the get_object_or_404 function for the state variable to grab only values that are associated with the disease_id. The code below does not work (it grabs all values in the State table. Any ideas?

views.py

def option(request, disease_id, state_id):      state = get_object_or_404(State, relevantdisease=disease_id)     disease = get_object_or_404(Disease, pk=disease_id)      context = {'state': state, 'disease':disease }     return render(request, "option.html", context) 

models.py

class State(models.Model):     state = models.CharField(max_length=300, verbose_name='state')     relevantdisease = models.ForeignKey(Disease, verbose_name="disease") 
like image 928
nlr25 Avatar asked Aug 21 '13 05:08

nlr25


1 Answers

get_object_or_404 will only return one object. You need get_list_or_404 as there could be multiple states for one disease:

from django.shortcuts import get_list_or_404, get_object_or_404  def option(request, disease_id, state_id):      state = get_list_or_404(State, relevantdisease__pk=disease_id)     disease = get_object_or_404(Disease, pk=disease_id)      context = {'state': state, 'disease':disease }     return render(request, "option.html", context) 
like image 89
Burhan Khalid Avatar answered Sep 28 '22 20:09

Burhan Khalid