【问题标题】:Django get model by querystringDjango 通过查询字符串获取模型
【发布时间】:2017-08-18 08:15:24
【问题描述】:

我希望用户能够在 url 中传递一个查询字符串,例如 https://example.com/models?id=232。但查询字符串是可选的。所以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)

S 上面的代码中发生了什么:我想检查是否有查询字符串(即模型 ID)以及是否存在此模型。但是我的代码不起作用。如果这两个要求都不满足,它应该只加载 tests.html 而没有 id 并且没有任何错误。我怎样才能做到这一点? id 也应该只是数字 期待您的回答:D

【问题讨论】:

  • 你有什么错误吗?显示你的网址
  • 如果我在 url 中输入字符串而不是数字,则会出错
  • 显示网址​​,为您的问题添加完整的错误跟踪

标签: python django url views


【解决方案1】:

您将收到错误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,你也可以使用;

# ...
from django.http import Http404

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

    if id is not None and id.isdigit():
        try:
            obj = ModelName.objects.get(pk=id)
            context.update({'id': obj.id})
        except ModelName.DoesNotExist:
            raise Http404

    return render(request, 'tests.html', context)

【讨论】:

  • 如何在没有“.filter()”的情况下获取模型并且不会导致 404 错误?
猜你喜欢
  • 1970-01-01
  • 2014-06-27
  • 2013-01-02
  • 2014-02-09
  • 2011-06-20
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多