# 01.使用django实现前后端分离
[toc]{type: "ol", level: [2, 3, 4, 5]}
### 环境搭建
#### 查看项目环境
```python
pip list
```
#### 安装django环境
```python
pip install django
```
### 应用
#### 创建应用
```python
python manage.py startapp shop
# python ../../manage.py startapp shop
```
#### 注册应用
```python
### settings.dev
'shop.apps.ShopConfig',
```
### 模型类
#### 创建模型类
```python
### shop.models
from django.db import models
# Create your models here.
# 使类具有ORM的功能
class Category(models.Model):
name = models.CharField(max_length=20, verbose_name='分类名称')
def __str__(self):
# 设置在admin中显示的内容
return self.name
class Goods(models.Model):
name = models.CharField(max_length=20, verbose_name='商品名称')
desc = models.CharField(max_length=200, verbose_name='商品描述', null=True, blank=True)
# 外键字段
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="分类名称")
def __str__(self):
# 设置在admin中显示的内容
return self.name
```
#### 注册模型类
```python
### shop.admin
from django.contrib import admin
from .models import *
# 注册model,显示在后台管理界面
# Register your models here.
admin.site.register(Category)
admin.site.register(Goods)
```
### 数据迁移
#### 创建超级用户
```python
python manage.py createsuperuser
```
#### 进行数据迁移
```python
# cd root
python manage.py makemigrations
python manage.py migrate
```
### 路由分发
#### 创建文件
在shop下创建urls.py文件
#### 配置路由
```python
### project.urls
path('shop/', include('shop.urls', namespace='shop')),
```
```python
### shop.urls
from django.urls import path
from . import views
urlpatterns = [
path(r"", views.index, name='index')
]
```
### 视图搭建
```python
### shop.views
from django.http import JsonResponse
from django.core import serializers
from .models import *
# Create your views here.
# 如果以json或xml格式返回数据,则可以实现前后端分离
def index(request):
categorys = Category.objects.all()
categorys_json = serializers.serialize('json', categorys)
return JsonResponse(categorys_json, safe=False)
```
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)