django orm of Detailed

django built into orm, it allows us to operate very easy database.

Before watching this article, be sure you have made the right django project configuration.

1. Create a new class of models.py under app01

from django.db import models


# Create your models here.


class User(models.Model):
    # int id primary key auto_increment 
    id = models.AutoField(primary_key=True)
    # varchar username(255)
    username = models.CharField(max_length=255)
    password = models.CharField(max_length=255)

# 还有许多其他字段

2. Use the built-in database migration command django

python manage.py makemigrations
python manage.py migrate

Note: When we modify the database related to the operation of models, the above two commands should be executed. We django database to ensure consistency with the project file.

After the implementation we can see our database has been generated corresponding table.

3. The common method

# 可在views.py视图函数下使用User类

# 新增一条记录并返回记录对象
user_obj = User.objects.create(username='yyh',password='123')
# 或者
user_obj = User(username='yyh',password='123')
user_obj.save()


# 查 
user_obj_list = User.objects.filter(username='yyh')
# filter方法返回一个对象列表
user_obj = user_obj_list.first()
user_obj = user_obj_list=[0]
# 返回表中所有记录
user_obj_list = User.objects.all()

# 改
user_obj = User.objects.filter(username='yyh').first()
user_obj.username='yyh123'
user_obj.save() # 根据主键 update

# 删
user_obj = User.objects.filter(username='yyh').first()
user_Obj.delete()
# 或者删除全部
User.objects.filter().delete()
User.objects.all().delete()

Guess you like

Origin www.cnblogs.com/Ghostant/p/12150102.html