从需求分析中可以看出,业务基本上是围绕着「产品」的
python -m manage.py startapp product
将新建的product
文件夹移动到apps
文件夹下
在backend/LightSeeking/settings.py
的INSTALLED_APPS
中注册新建的「产品」应用
INSTALLED_APPS = [
...
'users.apps.UsersConfig',
'product.apps.ProductConfig',
]
在全部业务相关的表中有几个通用的字段
提取到backend/utils/models.py
from django.db import models
class BaseModel(models.Model):
"""
基类,公共字段
"""
id = models.AutoField(verbose_name='id主键', primary_key=True, help_text='id主键')
c_time = models.DateTimeField('创建时间', auto_now_add=True)
u_time = models.DateTimeField('更新时间', auto_now=True)
is_delete = models.BooleanField('逻辑删除', default=False)
class Meta:
# 抽象类,用于继承,迁移时不会创建
abstract = True
使用abstract = True
后这个表结构就是一个表结构的基类了,其他表的创建就可以继承它了
产品包含了
from django.db import models
from utils.models import BaseModel
class Product(BaseModel):
product_id = models.CharField('货品编码', max_length=, unique=True, help_text='货品编码')
category = models.CharField('类别', max_length=, null=True, blank=True, default='', help_text='类别')
brand = models.CharField('品牌', max_length=, null=True, blank=True, default='', help_text='品牌')
name = models.CharField('品名', max_length=, null=True, blank=True, default='', help_text='品名')
price = models.DecimalField('产品单价', max_digits=, decimal_places=, default=, help_text='产品单价')
sample_png = models.CharField("样图", max_length=, null=True, blank=True, default='', help_text='样图')
desc = models.CharField('备注', max_length=, null=True, blank=True, default='', help_text='备注')
class Meta:
db_table = 'tb_product'
verbose_name = '产品信息'
verbose_name_plural = verbose_name
def __str__(self):
return self.product_id
python manage.py makemigrations
python manage.py migrate
read_only
is_delete
from rest_framework import serializers
from product.models import Product
class ProductModelSerializer(serializers.ModelSerializer):
class Meta:
model = Product
exclude = ('is_delete',)
extra_kwargs = {
'c_time': {
'read_only': True
}
}
from rest_framework.viewsets import ModelViewSet
from product.models import Product
from product.serializers import ProductModelSerializer
from utils.pagination import TenItemPerPagePagination
class ProductViewSet(ModelViewSet):
queryset = Product.objects.filter(is_delete=False).order_by("-c_time")
serializer_class = ProductModelSerializer
pagination_class = TenItemPerPagePagination
is_delete=False
backend/apps/product/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from product import views
router = DefaultRouter()
router.register("product", views.ProductViewSet)
urlpatterns = [
path('', include(router.urls))
]
backend/LightSeeking/urls.py
...
urlpatterns = [
...
path('', include('product.urls')),
]
访问http://127.0.0.1:8000/product/