本文主要是介绍5.5Django网络框架(5):数据模型详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
@说明
- 本文通过一个趣味的电商系统案例,演示Django框架中数据模型的使用
- 本例源代码的GitHub地址:https://github.com/ouyangsuo/WhatsDjangoModel
@创建数据模型
- 在子应用目录MyApp中创建数据模型,代码如下
from django.db import models# Create your models here.
class Buyer(models.Model):bname = models.CharField(max_length=20, unique=True)bgender = models.NullBooleanField(default=None)bage = models.IntegerField(default=0)def __str__(self):return self.bnameclass Account(models.Model):amoney = models.FloatField(default=100)ano = models.CharField(max_length=10, unique=True)apwd = models.CharField(max_length=6,default='111111')abuyer = models.OneToOneField(Buyer)def __str__(self):return self.anoclass Order(models.Model):# ono = models.AutoField(primary_key=True,default=1)odatetime = models.DateTimeField(auto_now_add=True)omoney = models.FloatField(default=0)omsg = models.CharField(max_length=200,null=True)obuyer = models.ForeignKey(Buyer)def __str__(self):return "Order{obuyer="+self.obuyer.bname+",omoney="+str(self.omoney)+"}"class Goods(models.Model):gname = models.CharField(max_length=20, unique=True)gtype = models.CharField(max_length=10)gprice = models.FloatField(default=0)ginfo = models.TextField()gbuyers = models.ManyToManyField(Buyer)def __str__(self):return self.gname
@创建和注册后台数据管理类
from django.contrib import admin# Register your models here.
from MyApp.models import *class BuyerAdmin(admin.ModelAdmin):# bname = models.CharField(max_length=20, unique=True)# bgender = models.NullBooleanField(default=None)# bage = models.IntegerField(default=0)def tellBgender(self):if self.bgender:return '男'else:return '女'list_display = ['bname',tellBgender,'bage']search_fields = ['bname']list_filter = ['bgender','bage']class AccountAdmin(admin.ModelAdmin):# amoney = models.FloatField(default=100)# ano = models.CharField(max_length=10, unique=True)# apwd = models.CharField(default='111111')# abuyer = models.OneToOneField(Buyer)list_display = ['ano','apwd','abuyer']search_fields = ['ano']list_filter = ['amoney']class GoodsAdmin(admin.ModelAdmin):# gname = models.CharField(max_length=20, unique=True)# gtype = models.CharField(max_length=10)# gprice = models.FloatField(default=0)# ginfo = models.TextField()# gbuyers = models.ManyToManyField(Buyer)list_display = ['gname','gtype','gprice','ginfo']search_fields = ['gname','gprice','gbuyers']list_filter = ['gprice','gtype']class MySite(admin.AdminSite):site_header = '美剁购物系统'site_title = '美剁'
mysite = MySite()mysite.register(Buyer,BuyerAdmin)
mysite.register(Account,AccountAdmin)
mysite.register(Goods,GoodsAdmin)
@执行数据迁移
python manage.py makemigrations
python manage.py migrate
@在管理后台插入买家、账户、商品数据
- 添加数据后的表内容为
@定义路由分发规则
- 在工程中将美剁meiduo/开头的路由全部交由MyAPP下的urls.py进行分发
from django.conf.urls import url, include
from django.contrib import admin
from MyApp.admin import mysiteurlpatterns = [url(r'^admin/', mysite.urls),# 将meiduo开头的路由交由MyApp.urls进行分发url(r'^meiduo/', include('MyApp.urls')),
]
- 定义应用MyApp内部的派发规则,主要实现增删改查和关联关系管理
from django.conf.urls import url, include
from django.contrib import adminfrom MyApp import views
from MyApp.admin import mysiteurlpatterns = [# 买家的增删改查路由url(r'^addbuyer/', views.addBuyer),url(r'^deletebuyer/', views.deleteBuyer),url(r'^updatebuyer/', views.updateBuyer),url(r'^querybuyer/', views.queryBuyer),# 一对一:获取用户的账户信息url(r'^getaccount/(\d+)/', views.getAccount),# 多对多:购买商品,获取用户购买的所有商品,查询商品的所有买家url(r'^buy/(\d+)/(\d+)/', views.buy), url(r'^getbuyergoods/(\d+)/', views.getBuyerGoods),url(r'^getgoodsbuyers/(\d+)/', views.getGoodsBuyers),# 一对多:查询用户的所有订单url(r'^getorders/(\d+)/', views.getOrders), ]
@实现用户数据的增删改查
- 在应用目录MyApp下实现对用户的增删改查
# 添加以时间戳明明的新用户
def addBuyer(request):b = Buyer()b.bname = 'Buyer-' + str(int(time.time()))b.save()return HttpResponse('用户添加成功' + b.bname)# 删除最后一个用户
def deleteBuyer(request):b = Buyer.objects.last()b.delete()return HttpResponse('用户删除成功' + b.bname)# 修改用户名称
def updateBuyer(request):b = Buyer.objects.last()b.bname = 'new' + b.bnameb.save()return HttpResponse('用户修改成功' + b.bname)# 查询所有用户
def queryBuyer(request):bs = Buyer.objects.all()ret = ''for b in bs:ret += b.bname + ";"return HttpResponse('用户查询成功' + ret)
- 在应用的views.py中实现关联关系的查询
# 一对一:获取用户的账户信息
def getAccount(request, bid):b = Buyer.objects.get(pk=bid)account = b.accountreturn HttpResponse(account.ano)# 用户购买商品
def buy(request, bid, gid):b = Buyer.objects.get(pk=bid)g = Goods.objects.get(pk=gid)g.gbuyers.add(b)g.save()o = Order()o.obuyer = bo.omoney = g.gpriceo.omsg = g.gnameo.save()return HttpResponse(o)# 一对多:查看用户的所有订单
def getOrders(request, bid):b = Buyer.objects.get(pk=bid)bos = b.order_set.all()ret = ''for o in bos:ret += str(o.id) + ";"return HttpResponse(ret)# 多对多:查看用户购买的全部商品
def getBuyerGoods(request, bid):b = Buyer.objects.get(pk=bid)gs = b.goods_setret = ''for g in gs:ret += g.gname + ";"return HttpResponse(ret)# 多对多:查看商品的全部买家
def getGoodsBuyers(request, gid):g = Goods.objects.get(pk=gid)bs = g.gbuyers.all()ret = ''for b in bs:ret += b.bname + ";"return HttpResponse(ret)
这篇关于5.5Django网络框架(5):数据模型详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!