在项目的配置文件 settings.py
中, INSTALLED_APPS 配置项 加入如下内容
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 加入下面这行 'common.apps.CommonConfig', ]
‘common.apps.CommonConfig’ 告诉 Django , CommonConfig 是 common/apps.py 文件中定义的一个应用配置的类。
是这样的
from django.apps import AppConfig class CommonConfig(AppConfig): name = 'common'
打开 common/models.py,发现里面是空的,因为我们还没有定义我们的业务所需要的表。
我们修改它,加入如下内容
from django.db import models # Create your models here. from django.db import models import datetime class Customer(models.Model): name = models.CharField(max_length=200) phonenumber = models.CharField(max_length=200) address = models.CharField(max_length=200) class Medicine(models.Model): # 药品名 name = models.CharField(max_length=200) # 药品编号 sn = models.CharField(max_length=200) # 描述 desc = models.CharField(max_length=200) class Order(models.Model): # 订单名 name = models.CharField(max_length=200,null=True,blank=True) # 创建日期 create_date = models.DateTimeField(default=datetime.datetime.now) # 客户 customer = models.ForeignKey(Customer,on_delete=models.PROTECT) # 订单购买的药品,和Medicine表是多对多 的关系 medicines = models.ManyToManyField(Medicine, through='OrderMedicine') # 为了提高效率,这里存放 订单 medicines 冗余数据 medicinelist = models.CharField(max_length=2000, null=True, blank=True) class OrderMedicine(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT) medicine = models.ForeignKey(Medicine, on_delete=models.PROTECT) # 订单中药品的数量 amount = models.PositiveIntegerField() # 国家表 class Country(models.Model): name = models.CharField(max_length=100) # country 字段是国家表的外键,形成一对多的关系 class Student(models.Model): name = models.CharField(max_length=100) grade = models.PositiveSmallIntegerField() country = models.ForeignKey(Country, on_delete = models.PROTECT, # 指定反向访问的名字 related_name='students')
执行命令生效:
python manage.py makemigrations common python manage.py migrate