Django-orm

Django项目中建立app01

python manage.py startapp app01

项目中的__init__设置

import pymysql
pymysql.install_as_ MYSQLdb()

setting中的设置

设置默认使用mysql数据库
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bms',  # 要链接的数据库
        'USER': 'root',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': '3306'

    }
}
设置将python语句转换成mysql指令在日志打印
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

 setting中的

INSTALLED_APPS配置,不然不会生成对应app的数据库
'app01.apps.App01Config'

建立表

python manage.py makemigrations
python manage.py migrate

 单表查询

queryset
(1) all() :  调用者:objects管理器  返回queryset
(2) filter() :调用者:objects管理器  返回queryset
(3) get方法():调用者:objects管理器  返回查询到model对象 (注意:查询结果有且只有一个才执行)
(4) first(),last()方法:调用者:queryset   返回model对象
(5) exclude():调用者:objects管理器  返回queryset
(6) order_by():由queryset对象调用,返回值是queryset
(7) count :数数  :由queryset对象调用 返回int
(8) reverse():由queryset对象调用,返回值是queryset
(9) exists(): 由queryset对象调用 返回值布尔值
(10)values()方法: 由queryset对象调用,返回值是queryset
(11)values_list():由queryset对象调用,返回值是queryset
(12)distinct(): 由queryset对象调用,返回值是queryset

模糊查询

模糊查询(双下划线)
Book.objects.filter(price__in=[100,200,300])
Book.objects.filter(price__gt=100)
Book.objects.filter(price__lt=100)
Book.objects.filter(price__range=[100,200])
Book.objects.filter(title__contains="python")
Book.objects.filter(title__icontains="python")
Book.objects.filter(title__startswith="py")
Book.objects.filter(pub_date__year=2012)

  

原文地址:https://www.cnblogs.com/jiaqi-666/p/9837477.html