gpt4 book ai didi

python - QuerySet 在 shell 中工作但不在 Views.py 中工作 - Django 1.10

转载 作者:行者123 更新时间:2023-12-01 03:17:23 25 4
gpt4 key购买 nike

在 Django shell (python manage.py shell) 中执行以下 QuerySet 时:

Employee.objects.filter(restaurant__pk = 1)

我得到结果:

<QuerySet [<Employee: Joyce McDonnals>]>

请原谅,因为我是 Django 新手。我正在尝试通过 PK 在我的网页中动态实现此查询集。我在views.py中定义的get_queryset是:

class EmployeeList(ListView):
template_name= "Restaurants/employee_list.html"
model = Employee
def get_queryset(self, **kwargs):
queryset = Employee.objects.filter(pk= restaurant.pk)
return queryset

但这会返回错误:

NameError at /restaurant/1/employees/
name 'restaurant' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8001/restaurant/1/employees/
Django Version: 1.10.5
Exception Type: NameError
Exception Value:
name 'restaurant' is not defined

我在views.py中尝试了查询集的一些变体,但我似乎无法让它工作。有人可以帮我定义这个查询集吗?

最佳答案

问题不在于查询集,而在于标准的 Python 作用域。您需要考虑餐厅的值(value)从何而来。

就您而言,它显然来自 URL;假设您有一个类似这样的 URL:

url(r'^restaurant/(?P<restaurant_id>\d+)/employees/$', ...)

命名捕获组,该值将存储在self.kwargs['restaurant_id']中。所以你应该在过滤器中使用它。

另请注意,您可以直接使用 restaurant_id 作为字段,而不是进行 JOIN

所以:

queryset = Employee.objects.filter(restaurant_id=self.kwargs['restaurant'])

关于python - QuerySet 在 shell 中工作但不在 Views.py 中工作 - Django 1.10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42343494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com