我正在尝试访问链接“ http://127.0.0.1:8000/products/2”,其中使用的是通用视图(DetailsView),在该视图中我想使用自定义模型管理器。但是我收到指出AttributeError的错误:“产品”对象没有属性“过滤器”。
我正在使用python版本3.8和Django版本2.2.6
# ModelManager
#-----------------------------------------------
class ProductManager(models.Manager):
def get_by_id(self,id):
qs = self.get_queryset().filter(id=id)
if qs.count() == 1:
return qs.first()
return None
# View
#-----------------------------------------------
class ProductDetailView(DetailView):
# queryset = Product.objects.all( )
def get_queryset(self, *args, **kwargs):
request = self.request
pk = self.kwargs.get("pk")
instance = Product.objects.get_by_id(pk)
if instance is None:
raise Http404("Product Couldn't be found")
return instance
Internal Server Error: /products/2
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/detail.py", line 106, in get
self.object = self.get_object()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/detail.py", line 36, in get_object
queryset = queryset.filter(pk=pk)
AttributeError: 'Product' object has no attribute 'filter'
[22/Oct/2019 18:51:56] "GET /products/2 HTTP/1.1" 500 75133
答案 0 :(得分:0)
get_queryset(..)
[Django-doc]需要一个 queryset ,而不是实例。您应该改用get_object(..)
[Django-doc]:
class ProductDetailView(DetailView):
def get_object(self, *args, **kwargs):
request = self.request
pk = self.kwargs.get('pk')
instance = Product.objects.get_by_id(pk)
if instance is None:
raise Http404('Product Couldn't be found')
return instance
覆盖get_queryset
失败的原因是,如果返回单个Product
对象,则默认get_object
将调用get_queryset
,然后调用{{ 1}}。但是,一个.filter(..)
当然没有Product
方法。
请注意,将您的经理实施为:
.filter(..)
因为在这里,我们只会对数据库进行一个查询,而不是多个查询。