我希望用户能够像https://example.com/models?id=232
一样在url中传递查询字符串。但是查询字符串是可选的。所以https://example/models
也应该起作用。我正在尝试这个:
def myview(request, model):
context = {
'model': model,
}
if request.GET.get('id', None) != None and Model.objects.get(pk=request.GET.get('id', None)).exists():
id = request.GET.get('id', None)
context['id'] = id
return render(request, 'tests.html', context)
else:
return render(request, 'tests.html', context)
上面的代码是怎么回事:我想检查是否有一个查询字符串(它是models id)以及是否存在这个模型。Bu tmy代码不工作。如果这两个要求都不满足,它应该只加载tests.html
,而不加载id
,并且没有任何错误。我怎么能做到呢?而且id
应该是数字
期待您的回答:D
您将得到一个错误
AttributeError: 'ModelName' object has no attribute 'exists'
,因为.exists()
函数可用于.filter(...)
方法。在另一种方法,您也可以使用
^{pr2}$ModelName.DoesNotExist
相关问题 更多 >
编程相关推荐