我正在使用Django版本3,当我尝试使用模型管理器时出现此错误 ModelManager出现错误
models.py
class ProductManager(models.Manager):
def get_queryset(self):
return ProductQuerySet(self.model, using=self._db)
def features(self):
return self.get_queryset().featured()
def get_by_id(self, id):
qs = self.get_queryset().filter(id=id)
if qs.count() == 1:
return qs.first()
return None
views.py
class ProductDetailView(DetailView):
template_name = "Products/details.html"
def get_context_data(self, *args, **kwargs):
context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
print(context)
return context
def get_object(self, *args, **kwargs):
request = self.request
pk = self.kwargs.get('pk')
instance = Product.objects.get_by_id
if instance is None:
raise Http404('Product does not exist')
return instance
错误:
AttributeError: 'Manager' object has no attribute 'get_by_id'
答案 0 :(得分:0)
好吧,问题在于Django模型对象查询集没有名为“ get_by_id”的方法。您应该只使用Django提供的功能。这可能就是您想要的:
Product.objects.get(id=1)
用所需的ID替换1。