Django-rest-framework的简单流程代码

  • 时间:
  • 来源:互联网
  • 文章标签:

rest_framework

以查询接口为例

1、model

# 微博类型
class WeiboType(models.Model):
    wtype = models.CharField(max_length=50, unique=True, verbose_name='微博类型')
    wnum = models.IntegerField(default=0, verbose_name='分类的微博数量')
    def __str__(self):
        return self.wtype
    class Meta:
        db_table = 'wtype'
        verbose_name = '微博类型表'
        verbose_name_plural = verbose_name
# 微博
class Weibo(models.Model):
    wtitle = models.CharField(max_length=100, verbose_name='微博名称')
    wcontent = models.TextField(verbose_name='微博内容')
    wtype = models.ForeignKey(to=WeiboType, on_delete=models.CASCADE)
    def __str__(self):
        return self.wtitle
    class Meta:
        db_table = 'weibo'
        verbose_name = '微博内容表'
        verbose_name_plural = verbose_name

2、url

# 主路由
path('weibo/', include('weibo.urls', namespace='weibo')),
# 子路由
path('index/', views.WIndex.as_view()),

3、views

from rest_framework.response import Response
from rest_framework.views import APIView

from weibo.models import Weibo
from weibo.serializers import WeiboSerializer

class WIndex(APIView):
    def get(self, request):
        weibo_info = Weibo.objects.all()
        print(weibo_info)

        # 序列化传出的weibo_info
        serializer = WeiboSerializer(weibo_info, many=True)
        print(serializer.data)

        # 需要将书转换成 JSON, 字典
        data = {
            'status': 200,
            'msg': 'ok',
            'data': serializer.data
        }
        return Response(data)

4、补充serializers.py
将queryset与model实例等进行序列化,转化成json格式,返回给用户(api接口)

    # 1.配置 Rest framework
    # 在settings.py
    # INSTALLED_APPS中加入'rest_framework'
    # 2.serializers.py
    # serializers定义了API的表现形式
    # 微博类型序列化
    class WeiboTypeSerializer(serializers.ModelSerializer):
        # 一对多时,为了多调一,显示一的信息
        class Meta:
            model = WeiboType
            fields = ("id", "wtype", "wnum")
    
    # 微博表序列化
    class WeiboSerializer(serializers.ModelSerializer):
        wtype = WeiboTypeSerializer()
    
        class Meta:
            model = Weibo
            fields = ("id", "wtitle", "wcontent", "wtype")

5.结果

 {
    "status": 200,
    "msg": "ok",
    "data": [
        {
            "id": 1,
            "wtitle": "吃饭饭",
            "wcontent": "happy",
            "wtype": {
                "id": 1,
                "wtype": "微博小说",
                "wnum": 0
            }
        },
        {
            "id": 2,
            "wtitle": "冰淇淋",
            "wcontent": "哈哈哈哈哈",
            "wtype": {
                "id": 1,
                "wtype": "微博小说",
                "wnum": 0
            }
        }
    ]
}

本文链接http://www.taodudu.cc/news/show-647630.html