irobot
irobot

Reputation: 31

ValueError : The QuerySet value for an exact lookup must be limited to one result using slicing

I'm getting this error when I shifted my code from Django 1.9 to django 2.2.9 version. It's perfectly working in django 1.9 but Can Anyone tell what has changed in 2.2.9 for this specific search. This is the Error I'm getting, I am stuck. I tried django doc. help!

def search(request):
    locations = Location.objects.all()#.order_by('location_name')
    departments = Department.objects.all()#.order_by('department_name')
    if not request.GET.get('location', 'none') == 'none' and not request.GET.get('specialty', 'none') == 'none':
        location = request.GET.get('location',None)
        specialty = request.GET.get('specialty',None)
        location = Location.objects.filter(location_name=location)
        hospitals = Hospital.objects.filter(location=location)
        # doctors = DoctorProfile.objects.filter(user.first_name__contains=first_name)
        doctors = []

        for hospital in hospitals:
            specialty = Department.objects.filter(department_name=specialty)
            doctors = DoctorProfile.objects.filter(hospital=hospital, specialization=specialty)

        return render(request, 'infrastructure/search.html', {'doctors': doctors, 'locations': locations, 'departments': departments})

    return render(request, 'infrastructure/search.html', {'locations': locations, 'departments': departments})

Upvotes: 1

Views: 1541

Answers (2)

irobot
irobot

Reputation: 31

Actually I figured out that I was passing location and specialty as a Query set. adding [0] with it makes it object. And with that It worked fine.

here is the code:

location = Location.objects.filter(location_name=location)[0]
hospitals = Hospital.objects.filter(location=location)

doctors = []

for hospital in hospitals:
    specialty = Department.objects.filter(department_name=specialty)[0]
    doctors=DoctorProfile.objects.filter(hospital=hospital, specialization=specialty)

Thanks For your help!!

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

location is a collection of Location objects. That collection can contain zero, one, or more elements, but it is still a collection.

In order to retrieve the hospitals, you can use the __in lookup [Django-doc]:

location = Location.objects.filter(location_name=location)
hospitals = Hospital.objects.filter(location__in=location)

or you can filter on the related model:

location = Location.objects.filter(location_name=location)
hospitals = Hospital.objects.filter(location__location_name=location)

Upvotes: 2

Related Questions