您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)django搭建項(xiàng)目配置環(huán)境和創(chuàng)建表的示例,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
1. 搭建項(xiàng)目配置環(huán)境和創(chuàng)建表
創(chuàng)建一個(gè)ttsx的項(xiàng)目
django-admin startproject ttsx
在ttsx下的__init__中導(dǎo)入mysql
import pymysql pymysql.install_as_MySQLdb()
配置mysql 讀寫(xiě)分離配置
# default:默認(rèn)的配置的是主數(shù)據(jù)庫(kù) 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'PORT': 3306, 'USER': 'root', 'PASSWORD': "mysql", 'NAME': "ttsx" }, # 配置的是從數(shù)據(jù)庫(kù) 'slave': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'PORT': 3306, 'USER': 'root', 'PASSWORD': "mysql", 'NAME': "ttsx" },
在項(xiàng)目的目錄下新建utils/db_router.py文件如下圖:
在 utils/db_router.py中定義一個(gè)數(shù)據(jù)庫(kù)路由,實(shí)現(xiàn)一個(gè)策略來(lái)控制特定模型的訪問(wèn)性
數(shù)據(jù)庫(kù)路由¶
數(shù)據(jù)庫(kù)路由是一個(gè)類,它提供4個(gè)方法:
db_for_read(model, **hints)¶
建議model類型的對(duì)象的讀操作應(yīng)該使用的數(shù)據(jù)庫(kù)。
如果一個(gè)數(shù)據(jù)庫(kù)操作能夠提供其它額外的信息可以幫助選擇一個(gè)數(shù)據(jù)庫(kù),它將在hints字典中提供。合法的hints 的詳細(xì)信息在下文給出。
如果沒(méi)有建議,則返回None。
db_for_write(model, **hints)¶
建議Model 類型的對(duì)象的寫(xiě)操作應(yīng)該使用的數(shù)據(jù)庫(kù)。
如果一個(gè)數(shù)據(jù)庫(kù)操作能夠提供其它額外的信息可以幫助選擇一個(gè)數(shù)據(jù)庫(kù),它將在hints字典中提供。 合法的hints 的詳細(xì)信息在下文給出。
如果沒(méi)有建議,則返回None。
allow_relation(obj1, obj2, **hints)¶
如果obj1 和obj2 之間應(yīng)該允許關(guān)聯(lián)則返回True,如果應(yīng)該防止關(guān)聯(lián)則返回False,如果路由無(wú)法判斷則返回None。這是純粹的
驗(yàn)證操作,外鍵和多對(duì)多操作使用它來(lái)決定兩個(gè)對(duì)象之間是否應(yīng)該允許一個(gè)關(guān)聯(lián)。
class MasterSlaveDBRouter(object): """讀寫(xiě)分離路由""" def db_for_read(self, model, **hints): """讀數(shù)據(jù)庫(kù)""" return "slave" def db_for_write(self, model, **hints): """寫(xiě)數(shù)據(jù)庫(kù)""" return "default" def allow_relation(self, obj1, obj2, **hints): """是否運(yùn)行關(guān)聯(lián)操作""" return True
在配置中聲明讀寫(xiě)分離路由所在的真正路徑:
DATABASE_ROUTERS = ["utils.db_router.MasterSlaveDBRouter"]
=========================================================================================================================================================
為類補(bǔ)充字段
在utils目錄中創(chuàng)建一個(gè)models.py用來(lái)'''為模型類補(bǔ)充字段'''的抽象類, 聲明一個(gè)類是抽象類,不遷移,專門給別的表繼承用的
在元選項(xiàng)中增添屬性 abstract=True
from django.db import models class BaseModel(models.Model): '''為模型類補(bǔ)充字段''' create_time=models.DateTimeField(auto_now_add=True,verbose_name='創(chuàng)建時(shí)間') update_time=models.DateTimeField(auto_now=True,verbose_name='更新時(shí)間') class Meta: abstract=True # 聲明是抽象模型類,不遷移,專門給別的表繼承用的
==========================================================================================================================================================
創(chuàng)建應(yīng)用
在項(xiàng)目隊(duì)根目錄下創(chuàng)建一個(gè)app目錄用來(lái)存儲(chǔ)所有的應(yīng)用:
分別創(chuàng)建 應(yīng)用 cart goods orders users
python ../manage.py startapp cart python ../manage.py startapp goods python ../manage.py startapp orders python ../manage.py startapp users
在goods應(yīng)用中的models中定義如下和商品相關(guān)的類:
from django.db import models from utils.models import BaseModel from tinymce.models import HTMLField # Create your models here. class GoodsCategory(BaseModel): """商品類別表""" name = models.CharField(max_length=20, verbose_name="名稱") logo = models.CharField(max_length=100, verbose_name="標(biāo)識(shí)") image = models.ImageField(upload_to="category", verbose_name="圖片") class Meta: db_table = "df_goods_category" verbose_name = "商品類別" # admin站點(diǎn)使用 verbose_name_plural = verbose_name def __str__(self): return self.name class Goods(BaseModel): """商品SPU表""" name = models.CharField(max_length=100, verbose_name="名稱") # desc = HTMLField(verbose_name="詳細(xì)介紹", default="", blank=True) 富文本編輯器 class Meta: db_table = "df_goods" verbose_name = "商品" verbose_name_plural = verbose_name def __str__(self): return self.name class GoodsSKU(BaseModel): """商品SKU表""" category = models.ForeignKey(GoodsCategory, verbose_name="類別") goods = models.ForeignKey(Goods, verbose_name="商品") name = models.CharField(max_length=100, verbose_name="名稱") title = models.CharField(max_length=200, verbose_name="簡(jiǎn)介") unit = models.CharField(max_length=10, verbose_name="銷售單位") price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="價(jià)格") stock = models.IntegerField(default=0, verbose_name="庫(kù)存") sales = models.IntegerField(default=0, verbose_name="銷量") default_image = models.ImageField(upload_to="goods", verbose_name="圖片") status = models.BooleanField(default=True, verbose_name="是否上線") class Meta: db_table = "df_goods_sku" verbose_name = "商品SKU" verbose_name_plural = verbose_name def __str__(self): return self.name class GoodsImage(BaseModel): """商品圖片""" sku = models.ForeignKey(GoodsSKU, verbose_name="商品SKU") image = models.ImageField(upload_to="goods", verbose_name="圖片") class Meta: db_table = "df_goods_image" verbose_name = "商品圖片" verbose_name_plural = verbose_name def __str__(self): return str(self.sku) class IndexGoodsBanner(BaseModel): """主頁(yè)輪播商品展示""" sku = models.ForeignKey(GoodsSKU, verbose_name="商品SKU") image = models.ImageField(upload_to="banner", verbose_name="圖片") index = models.SmallIntegerField(default=0, verbose_name="順序") class Meta: db_table = "df_index_goods" verbose_name = "主頁(yè)輪播商品" verbose_name_plural = verbose_name def __str__(self): return str(self.sku) class IndexCategoryGoodsBanner(BaseModel): """主頁(yè)分類商品展示""" DISPLAY_TYPE_CHOICES = ( (0, "標(biāo)題"), (1, "圖片") ) category = models.ForeignKey(GoodsCategory, verbose_name="商品類別") sku = models.ForeignKey(GoodsSKU, verbose_name="商品SKU") display_type = models.SmallIntegerField(choices=DISPLAY_TYPE_CHOICES, verbose_name="展示類型") index = models.SmallIntegerField(default=0, verbose_name="順序") class Meta: db_table = "df_index_category_goods" verbose_name = "主頁(yè)分類展示商品" verbose_name_plural = verbose_name def __str__(self): return str(self.sku) class IndexPromotionBanner(BaseModel): """主頁(yè)促銷活動(dòng)展示""" name = models.CharField(max_length=50, verbose_name="活動(dòng)名稱") url = models.URLField(verbose_name="活動(dòng)連接") image = models.ImageField(upload_to="banner", verbose_name="圖片") index = models.SmallIntegerField(default=0, verbose_name="順序") class Meta: db_table = "df_index_promotion" verbose_name = "主頁(yè)促銷活動(dòng)" verbose_name_plural = verbose_name def __str__(self): return self.name
在orders應(yīng)用中的models中定義如下和訂單相關(guān)的類:
from django.db import models from utils.models import BaseModel from users.models import User, Address from goods.models import GoodsSKU # Create your models here. class OrderInfo(BaseModel): """訂單信息""" PAY_METHOD_CHOICES = ( (1, "貨到付款"), (2, "支付寶"), ) ORDER_STATUS_CHOICES = ( (1, "待支付"), (2, "待發(fā)貨"), (3, "待收貨"), (4, "待評(píng)價(jià)"), (5, "已完成"), ) order_id = models.CharField(max_length=64, primary_key=True, verbose_name="訂單號(hào)") user = models.ForeignKey(User, verbose_name="下單用戶") address = models.ForeignKey(Address, verbose_name="收獲地址") total_count = models.IntegerField(default=1, verbose_name="商品總數(shù)") total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="商品總金額") trans_cost = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="運(yùn)費(fèi)") pay_method = models.SmallIntegerField(choices=PAY_METHOD_CHOICES, default=1, verbose_name="支付方式") status = models.SmallIntegerField(choices=ORDER_STATUS_CHOICES, default=1, verbose_name="訂單狀態(tài)") trade_id = models.CharField(max_length=100, unique=True, null=True, blank=True, verbose_name="支付編號(hào)") class Meta: db_table = "df_order_info" class OrderGoods(BaseModel): """訂單商品""" order = models.ForeignKey(OrderInfo, verbose_name="訂單") sku = models.ForeignKey(GoodsSKU, verbose_name="訂單商品") count = models.IntegerField(default=1, verbose_name="數(shù)量") price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="單價(jià)") comment = models.TextField(default="", verbose_name="評(píng)價(jià)信息") class Meta: db_table = "df_order_goods"
在users應(yīng)用中的models中定義如下和用戶相關(guān)的類:
from django.db import models from django.contrib.auth.models import AbstractUser from utils.models import BaseModel from django.conf import settings from goods.models import GoodsSKU from itsdangerous import TimedJSONWebSignatureSerializer as Serializer # Create your models here. # django默認(rèn)的認(rèn)證機(jī)制,在setting installAPPs中的 'django.contrib.auth', # 所以我們要聲明自己的認(rèn)證路徑 去setting配置,AUTH_USER_MODEL = "users.User" class User(AbstractUser, BaseModel): """用戶""" # 我們自己不用指明字段,django的默認(rèn)字段,都通過(guò)繼承AbstractUser它就有了 class Meta: db_table = "df_users" def generate_active_token(self): """生成激活令牌""" serializer = Serializer(settings.SECRET_KEY, 3600) token = serializer.dumps({"confirm": self.id}) # 返回bytes類型 return token.decode() class Address(BaseModel): """地址""" user = models.ForeignKey(User, verbose_name="所屬用戶") receiver_name = models.CharField(max_length=20, verbose_name="收件人") receiver_mobile = models.CharField(max_length=11, verbose_name="聯(lián)系電話") detail_addr = models.CharField(max_length=256, verbose_name="詳細(xì)地址") zip_code = models.CharField(max_length=6, verbose_name="郵政編碼") class Meta: db_table = "df_address"
==============================================================================================================================================================================
用戶認(rèn)證模型類
在配置文件中,指定自己定義的認(rèn)證系統(tǒng)使用的用戶模型路徑在user應(yīng)用中的User類,django只支持模塊和類名之間用.分隔,多了一個(gè)點(diǎn)就解析不出來(lái),
如這樣就解析不出來(lái),AUTH_USER_MODEL = "apps.users.User" Django,所以要把它變成,users.User,所以將apps目錄添加到解析路徑里
import sys sys.path.insert(1, os.path.join(BASE_DIR, "app")) #認(rèn)證系統(tǒng)使用的用戶模型 AUTH_USER_MODEL = "users.User"
把注冊(cè)的應(yīng)用 添加到配置文件的INSTALLED_APPS中,因?yàn)樯厦嬖?自定義用戶認(rèn)證模型類的時(shí)候,已經(jīng)把a(bǔ)pp目錄添加到解析路徑里了,所以不用app.users這樣添加,直接寫(xiě)應(yīng)用的名字:
================================================================================================================================================================================
創(chuàng)建數(shù)據(jù)庫(kù)
create database ttsx charset=utf8;
執(zhí)行遷移
python manage.py makemigrations python manage.py migrate
關(guān)于“django搭建項(xiàng)目配置環(huán)境和創(chuàng)建表的示例”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。