39

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

3 Answers 3

64

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)
0
4

I'm surprised that's not 404'ing, actually. Try this:

state = get_object_or_404(State, relevantdisease_id=disease_id)

Or, if you prefer, this:

disease = get_object_or_404(Disease, pk=disease_id)
state = get_object_or_404(State, relevantdisease=disease)

The point is that the relevantdisease field expects filters to use the actual Disease model, not the PK. You can use the PK if you filter on the implicit ID field, as in my first example, or fetch a Disease object and filter using that. The latter would be inefficient if you didn't need the Disease instance anyway, but your example shows you retrieving it regardless so fetching it first won't cost you any performance.

3

I think you are missing something with your models.

You have ForeighKey() with Disease in State model. What that means is there are many States for one Disease.

So when you do get_object_or_404(State, relevantdisease_id=disease_id) you will get all State objects for that disease_id.

You may want to use get_list_or_404() and work with either the list of State objects or choose one with whatever criteria you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.