django的models新增数据库表时,如果不设置主键,会默认新增一个id为主键,如果我们想自己设置一个字段为主键,需加个参数primary_key=True
默认id主键新增一张用户表,表名为user 字段user_name, psw ,mail 都是字符串类型,设计如下
# models.py
from django.db import models
# Create your models here.
# 我们新建了一个Person类,继承自models.Model,
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
# 新增一张用户表,表名为user 字段user_name, psw ,mail 都是字符串类型
class User(models.Model):
user_name = models.CharField(max_length=30)
psw = models.CharField(max_length=30)
mail = models.CharField(max_length=30)
cmd执行makemigrations和migrate
python manage.py makemigrations
python manage.py migrate
然后就可以看到hello_user表新增成功了,默认多一个字段id为主键
设置主键primary_key新增一张用户表,表名为user 字段user_name(主键), psw ,mail 都是字符串类型,我们设置user_name为主键,让用户名不重复,设计如下
# models.py
from django.db import models
# Create your models here.
# 我们新建了一个Person类,继承自models.Model,
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
# 新增一张用户表,表名为user 字段user_name, psw ,mail 都是字符串类型
class User(models.Model):
user_name = models.CharField(max_length=30,
primary_key=True) # 设置为主键
psw = models.CharField(max_length=30)
mail = models.CharField(max_length=30)
cmd执行makemigrations和migrate
python manage.py makemigrations
python manage.py migrate
然后就可以看到hello_user表新增成功了,主键user_name就会代替默认的id主键了
django交流QQ群:779429633