Django模型增加字段

 增加字段的操作

from django.db import models
import datetime
# Create your models here.

# 图书类
class BookInfo(models.Model):
    """图书模型类"""
    #图书名称:CharField说明是一个字符串,指定字符串最大长度
    btitle = models.CharField(max_length=20)


    #后期增加图书出版日期:DateField说明是一个日期类型
    bpub_date = models.DateField(auto_now_add=True)

 

python manage.py makemigrations

选择选项1,按回车。添加新字段。生成迁移文件

python manage.py migrate

(venv) G:\Python\git\python\05-Django\HelloWorld>python manage.py makemigrations
You are trying to add the field 'bpub_date' with 'auto_now_add=True' to bookinfo without a default; the database needs something to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
[default: timezone.now] >>>
Migrations for 'django_webapp':
  django_webapp\migrations\0003_bookinfo_bpub_date.py
    - Add field bpub_date to bookinfo

(venv) G:\Python\git\python\05-Django\HelloWorld>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, django_webapp, sessions
Running migrations:
  Applying django_webapp.0003_bookinfo_bpub_date... OK

 python manage.py shell

进入交互式解释器

>>> from django_webapp.models import BookInfo

from 应用名.models import 类名

>>> BookInfo.objects.all().values()

显示数据


(venv) G:\Python\git\python\05-Django\HelloWorld>python manage.py shell
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django_webapp.models import BookInfo
>>> BookInfo.objects.all().values()

>>>

 增加数据

>>> x=BookInfo()
>>> x.btitle='天龙八部'
>>> import datetime
>>> x.bpub_date=datetime.date(2020,11,7)
>>> x.save()
>>> BookInfo.objects.all().values()

更新数据

>>> x.bpub_date=datetime.date(2022,10,8)
>>> x.save()
>>> BookInfo.objects.all().values()

删除数据 

>>> z=BookInfo.objects.get(id=1)
>>> z.btitle
'aaa'
>>> z.delete()
(1, {'django_webapp.BookInfo': 1})

 

你可能感兴趣的:(Django)