4、数据模型的搭建与使用
1、介绍
- Django对各种数据库都提供了很好的支持,包括:PostgreSQL、MySQL、SQLite 和 Oracle,且为这些数据库提供了统一的API方法,这些API称为ORM框架,通过使用Django内置的ORM框架可以实现数据库的连接与读取操作。
- ORM框架是一种程序技术,用于实现面向对象程序语言在不同类型系统的数据之间的转换,从效果上来说,它创建了一个可在编辑语言中的虚拟对象数据库,通过对虚拟数据库的操作来实现对目标数据库的操作,虚拟对象数据库与目标数据库是相互对象的。
2、Model设计
- 修改 commodity应用下的models.py
from django.db import models
class Types(models.Model):
id = models.AutoField(primary_key=True)
firsts = models.CharField('一级类型', max_length=100)
seconds = models.CharField('二级类型', max_length=100, unique=True)
def __str__(self):
return str(self.id)
class Meta:
verbose_name = '商品类型'
verbose_name_plural = verbose_name
db_table = 'types'
class CommodityInfos(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField('商品名称', max_length=100)
sezes = models.CharField('颜色规格', max_length=100)
price = models.FloatField('商品价格')
discount = models.FloatField('折后价格')
stock = models.IntegerField('存货数量')
sold = models.IntegerField('已售数量')
likes = models.IntegerField('收藏数量')
created = models.DateField('上架日期', auto_now_add=True)
img = models.FileField('商品主图', upload_to=r'imgs')
details = models.FileField('商品介绍', upload_to=r'details')
types = models.ForeignKey(Types, on_delete=models.SET_NULL, null=True, to_field='seconds', verbose_name='商品类型')
def __str__(self):
return str(self.i