python - 在 Get 请求中返回对象时出现 AttributeError '' 对象没有属性 'get'

标签 python django django-templates django-views

这是请求网址:GET/api/v1/companies/profile/?name=TestFirma 我对 django 比较陌生,这是我第一次尝试在 django 中使用 GET 请求传递参数。

我已经使用记录器进行了测试,名称(TestFirma)实际上传递给 get_object。

我不明白为什么 Company 应该有一个 get 方法?我在这里误解了什么?

def get_object(request, name):
    name = request.GET.get('name', '')
    if name is not None:
        company = Company.objects.get(name=name)
        return company

堆栈:

[04/Jan/2016 13:40:49] "GET /static/templates/company/profile.html HTTP/1.1" 200 133
Internal Server Error: /api/v1/companies/profile/
Traceback (most recent call last):
  File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\core\handlers\base.py", line 223, in get_response
    response = middleware_method(request, response)
  File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\middleware\clickjacking.py", line 31, in process_response
    if response.get('X-Frame-Options', None) is not None:
AttributeError: 'Company' object has no attribute 'get'
Internal Server Error: /api/v1/companies/profile/
Traceback (most recent call last):
  File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\core\handlers\base.py", line 223, in get_response
    response = middleware_method(request, response)
  File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\middleware\clickjacking.py", line 31, in process_response
    if response.get('X-Frame-Options', None) is not None:
AttributeError: 'Company' object has no attribute 'get'
[04/Jan/2016 13:40:49] "GET /api/v1/companies/profile/?name=TestFirma HTTP/1.1" 500 75282
[04/Jan/2016 13:40:49] "GET /favicon.ico HTTP/1.1" 200 6524

最佳答案

我假设您想要返回 Company 对象的 JSON 响应。如果这就是您想要的,那么您应该序列化该对象,然后将其作为 HttpResponse 对象返回。

import json

from django.http import HttpResponse
from django.core import serializers

def get_object(request, name):
    name = request.GET.get('name', '')
    if name is not None:
        obj = Company.objects.get(name=name)
        company = serializers.serialize('json', [obj,])
        struct = json.loads(company)
        data = json.dumps(struct[0])
        return HttpResponse(data, content_type='json')

关于python - 在 Get 请求中返回对象时出现 AttributeError '' 对象没有属性 'get',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34591532/

相关文章:

html - 在Google Chrome中播放AVI视频

python - Combinatorics Counting Puzzle : Roll 20, 8面骰子,得到至少5个相同值的骰子的概率是多少

python - 在 numpy 或 scipy 中有效计算 3d 旋转矩阵列表

python - 仅使用特定 Csv 列的 KMeans 聚类

python - 重定向到另一个域的 Django View

django - 如何向无序列表的输出添加属性?

python - numpy 从线性函数生成数据

python - 无法使用 apache mod WSGI 在 ubuntu 上部署 Django

django - 无法通过 Django View 打开作为附件返回的 XLS

python - 如何在django中的单个 View 中显示多个ForeignKey过滤项?