python-0009-django对数据的增删改

shell

在虚拟环境中,可以使用python manage.py shell,打开命令行。在命令行中,所见即所得,相当于执行代码片段

对象

from django.db import models

# Create your models here.

class BookInfo(models.Model):
    name = models.CharField(max_length=10,unique=True)
    pub_date = models.DateTimeField(null=True)
    read_count = models.IntegerField(default=0)
    commentcount = models.IntegerField(default=0)
    is_delete = models.BooleanField(default=False)

    class Meta:
        # 修改表的名称
        db_table = 'bookinfo'
        # 站点使用
        verbose_name = '书籍管理'


class PeopleInfo(models.Model):
    # 创建字典
    GENDER_CHOICE = (
        (0,'male'),
        (1,'female')
    )
    name = models.CharField(max_length=10, verbose_name='名称')
    gender = models.SmallIntegerField(choices=GENDER_CHOICE,default=0,verbose_name='性别')
    description = models.CharField(max_length=300,verbose_name='描述',null=True)
    is_delete = models.BooleanField(default=False,verbose_name='逻辑删除')
    book = models.ForeignKey(BookInfo,on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    class Meta:
        # 修改表的名称
        db_table = 'peopleinfo'
        # 站点使用
        verbose_name = '读者信息'

创建一个python

创建crud-demo.py,用来写代码(方便),之后拷贝到shell里面
from book.models import BookInfo

# 1.新增
# 方式1
book = BookInfo(
    name="完美世界",
    pub_date= "2019-01-01",
    read_count=10000,
    commentcount=1000000
);
# 手动保存
book.save()


# 方式2
BookInfo.objects.create(
    name="斗罗大陆",
    pub_date= "2018-10-01",
    read_count=2000,
    commentcount=200000
);

# 修改
# 方式1
book = BookInfo.objectt.get(id=3)
book.read_count = 300000
book.save()

# 方式2
column = BookInfo.objects.filter(id=6).update(read_count=6000)
print(column)

# 删除
# 方式1
BookInfo.objects.filter(id=6).delete();
# 方式2
BookInfo.objects.get(id=8).delete();

你可能感兴趣的:(python,python,django,sqlite)