getting database values using get_object_or_404

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.


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)

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.

Tags:

Django