Django 모델 추가 필드

2967 단어 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을 선택하고 Enter 키를 누릅니다.새 필드를 추가합니다.마이그레이션 파일 생성
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})

좋은 웹페이지 즐겨찾기