歡迎您光臨本站 註冊首頁

Django設置Postgresql的操作

←手機掃碼閱讀     e36605 @ 2020-06-04 , reply:0

這裡假定Postgresql數據庫已經裝好。

首先安裝依賴的包

$ sudo yum install python-devel postgresql-devel

如果使用virtualenv,先source一下virtualenv下的“ . bin/activate”,然後運行

$ pip install psycopg2

修改settings.py文件

 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '...', 'USER': '...', 'PASSWORD': '...', 'HOST': '127.0.0.1', 'PORT': '5432', } }


測試

 python manage.py shell >>> from django.db import connection >>> cursor = connection.cursor


如果沒有返回任何錯誤說明數據庫連接成功。

補充知識:Django orm 常用查詢篩選總結

本文主要列舉一下django orm中的常用查詢的篩選方法:

大於、大於等於

小於、小於等於

in

like

is null / is not null

不等於/不包含於

其他模糊查詢

model:

 class User(AbstractBaseUser, PermissionsMixin): uuid = ShortUUIDField(unique=True) username = models.CharField(max_length=100, db_index=True, unique=True, default='') schoolid = models.CharField(max_length=100, null=True, blank=True, default='') classid = models.CharField(max_length=100, null=True, blank=True, default='') fullname = models.CharField(max_length=50, default='', null=True, blank=True) email = models.EmailField(_('email address'), blank=True, null=True) age = models.SmallIntegerField(default=0)


大於、大於等於

__gt 大於

__gte 大於等於

User.objects.filter(age__gt=10) // 查詢年齡大於10歲的用戶
User.objects.filter(age__gte=10) // 查詢年齡大於等於10歲的用戶

小於、小於等於

__lt 小於

__lte 小於等於

User.objects.filter(age__lt=10) // 查詢年齡小於10歲的用戶
User.objects.filter(age__lte=10) // 查詢年齡小於等於10歲的用戶

in

__in

查詢年齡在某一範圍的用戶

User.objects.filter(age__in=[10, 20, 30])

like

__exact 精確等於 like 'aaa'

__iexact 精確等於 忽略大小寫 ilike 'aaa'

__contains 包含 like '%aaa%'

__icontains 包含 忽略大小寫 ilike '%aaa%',但是對於sqlite來說,contains的作用效果等同於icontains。

is null / is not null

__isnull 判空

User.objects.filter(username__isnull=True) // 查詢用戶名為空的用戶
User.objects.filter(username__isnull=False) // 查詢用戶名不為空的用戶

不等於/不包含於

User.objects.filter().exclude(age=10) // 查詢年齡不為10的用戶
User.objects.filter().exclude(age__in=[10, 20]) // 查詢年齡不為在 [10, 20] 的用戶

其他模糊查詢

__startswith 以…開頭
__istartswith 以…開頭 忽略大小寫
__endswith 以…結尾
__iendswith 以…結尾,忽略大小寫
__range 在…範圍內
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日


[e36605 ] Django設置Postgresql的操作已經有230次圍觀

http://coctec.com/docs/python/shhow-post-236963.html