9. select
あいまい検索
users3 = User.objects.filter(username__startswith='koty')
# select id, username from user where username like 'koty%';
users4 = User.objects.filter(username__endswith='koty')
# select id, username from user where username like '%koty';
users5 = User.objects.filter(username__contains='koty')
# select id, username from user where username like '%koty%';
10. select
group by
from django.db.models import Count
Tag.objects.values('url')
.annotate(url_count=Count('url'))
.filter(url_count__gt=1)
# select url count(username) as url_count from tag group by url having
count(url)>1
12. update と delete
koty2.username = 'koty3'
koty2.save()
# update user set username='koty3' where id=2
koty2.delete()
# delete from user where id=2;
13. 外部キー先のデータの取得
p = Profile.objects.get(id=1)
u = p.user
profiles = Profile.objects.all()
for p in profiles:
print(p.user)
profiles = Profile.objects.select_related('user').all()
# select profile.id, profile.user_id, user.id, user.username
from user inner join user on profile.user_id=user.id
参照された時点で select が走る
N+1 問題
select_relatedでフィールドを指定すると
JOINになる