> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/python/django-rest-framework/5.1.-tong-guo-django-de-view-shi-xian-api.md).

# 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等多余字段
