【问题标题】:ValueError : The QuerySet value for an exact lookup must be limited to one result using slicingValueError :精确查找的 QuerySet 值必须使用切片限制为一个结果
【发布时间】:2020-11-13 10:39:01
【问题描述】:

当我将代码从 Django 1.9 转移到 django 2.2.9 版本时出现此错误。它在 django 1.9 中完美运行,但任何人都可以说出 2.2.9 中针对此特定搜索发生的变化。 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})

【问题讨论】:

    标签: python python-3.x django django-models django-views


    【解决方案1】:

    locationLocation 对象的集合。该集合可以包含零个、一个或多个元素,但它仍然是一个集合。

    为了检索医院,您可以使用__in lookup [Django-doc]

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

    或者您可以过滤相关模型:

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

    【讨论】:

      【解决方案2】:

      实际上,我发现我将位置和专业作为查询集传递。添加 [0] 使其成为对象。有了它,它工作得很好。

      代码如下:

      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)
      

      感谢您的帮助!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        • 2019-10-02
        • 2019-11-10
        • 2021-07-20
        • 2021-04-23
        • 1970-01-01
        相关资源
        最近更新 更多