美文网首页
设计数据库及通用视图实现api接口

设计数据库及通用视图实现api接口

作者: 爱修仙的道友 | 来源:发表于2019-04-24 22:44 被阅读0次

    一、设计数据库

    from django.db import models
    
    
    class GoodsCategory(models.Model):
        """商品类别"""
    
        name = models.CharField(max_length=30, verbose_name="类别名", help_text="类别名")
    
        create_time = models.DateTimeField("创建时间", auto_now_add=True)
        update_time = models.DateTimeField("更新时间", auto_now=True)
    
        class Meta:
            db_table = "tb_goods_Category"
            verbose_name = "商品类别"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    
    class Goods(models.Model):
        """商品"""
    
        category = models.ForeignKey(GoodsCategory, verbose_name="商品类目",on_delete=models.SET_NULL,null=True,blank=True)
    
        goods_sn = models.CharField(max_length=50, default="", verbose_name="商品唯一货号")
        name = models.CharField(max_length=100, verbose_name="商品名")
        sold_num = models.IntegerField(default=0, verbose_name="商品销售量")
        market_price = models.FloatField(default=0, verbose_name="市场价格")
        create_time = models.DateTimeField("创建时间", auto_now_add=True)
        update_time = models.DateTimeField("更新时间", auto_now=True)
    
        class Meta:
            db_table = "tb_goods"
            verbose_name = '商品'
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.name
    
    

    二、通用类视图

    from django.views import View
    from django.http import HttpResponse
    from django.core.serializers import serialize
    
    
    from . import models
    
    
    class GoodsListView(View):
        """商品列表"""
    
        def get(self, request):
            """
            通用View实现商品列表展示
            :param request:
            :return:
            """
    
            goods = models.Goods.objects.all()
            # django 提供的序列化器
            json_data = serialize("json", goods)
    
            return HttpResponse(json_data,content_type="application/json")
    
    

    三、路由配置

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('goods/',views.GoodsListView.as_view(),name='goods_list')
    ]
    

    四、postman接口测试


    image.png

    相关文章

      网友评论

          本文标题:设计数据库及通用视图实现api接口

          本文链接:https://www.haomeiwen.com/subject/bvhggqtx.html