Django通过查询字符串获取模型

2024-04-18 17:39:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户能够像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


Tags: 字符串httpsnoneidgetmodelreturnmodels
1条回答
网友
1楼 · 发布于 2024-04-18 17:39:23

您将得到一个错误AttributeError: 'ModelName' object has no attribute 'exists',因为.exists()函数可用于.filter(...)方法。在

def myview(request, model):
    id = request.GET.get('id', None)
    context = {'model': model, 'id': id}

    if id is not None and id.isdigit():
        if ModelName.objects.filter(pk=id).exists():
            context['id'] = id
    return render(request, 'tests.html', context)

另一种方法,您也可以使用ModelName.DoesNotExist

^{pr2}$

相关问题 更多 >