# 5.1.通过django的view实现api

## 基础实现

通过django的view实现商品列表页

```python
import json

from django.http import HttpResponse
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]
        for good in goods:
            json_dict = {}
            json_dict['name'] = good.name
            json_dict['category'] = good.category.name
            json_dict['market_price'] = good.market_price
            json_list.append(json_dict)

        return HttpResponse(json.dumps(json_list), content_type='application/json')
```

## 使用model\_to\_dict快速转换model为dict

```python
import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]

        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

        return HttpResponse(json.dumps(json_list), content_type='application/json')
```

存在问题：json库无法转换非原生python类型

报错TypeError: Object of type ImageFieldFile is not JSON serializable

## 使用serializers序列化对象为json

```python
import json

from django.http import HttpResponse
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]

        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

        from django.core import serializers
        json_data = serializers.serialize('json', goods)

        return HttpResponse(json_data, content_type='application/json')
```

## 使用JsonResponse简化HttpResponse

```python
import json

from django.http import HttpResponse
from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        json_list = []
        goods = Goods.objects.all()[:10]

        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(good)
            json_list.append(json_dict)

        from django.core import serializers
        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)

        from django.http import JsonResponse
        return JsonResponse(json_data, safe=False)
```

## 结果

```javascript
[
  {
    "model": "goods.goods",
    "pk": 1,
    "fields": {
      "category": 4,
      "name": "西班牙猪肉",
      "market_price": 0.0,
      ...
    }
  },
  ...
]
```

存在问题：结果格式不符合一般使用习惯，比如：主键在外，model、fields等多余字段


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://moluo.gitbook.io/notes/bian-cheng-xue-xi/python/django-rest-framework/5.1.-tong-guo-django-de-view-shi-xian-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
