Django 基础(二)

1. 多对多表之间的保存

方式一:

    u2 = User.objects.get(id=2)
    g2 = Group.objects.get(id=2)
    u2.group_relation.add(g2)    #在关系表中存入关联数据

方式二:

name = request.POST.get('name',None)
username = request.POST.get('username',None)
password = request.POST.get('password',None)
gplist = request.POST.getlist('groupId')
user = Users.objects.create(name=name,username=username,password=password)
user.save()
glist = UserGroup.objects.filter(id__in=gplist)
user.groupId.add(*glist)
# 或
#for gord in gplist:
#    group = UserGroup.objects.get(id=gord)
#    user.groupId.add(group)

方式三:

    u2 = User.objects.get(id=2)
    g2 = Group.objects.get(id=2)
    g2.user_set.add(u2)    #无多对多字段方添加关联, _set 是固定搭配,它的前面是多对多字段所在类的类名的小写

 

2. 多对多表之间的数据获取

    u2 = User.objects.get(id=2)
    g2 = Group.objects.get(id=2)
    print(u2.group_relation.all())
    print(u2.group_relation.all()).filter(id=1)
    print(u2.group_relation.all()).filter(caption='CEO')

3. Session

a)	request.session[‘is_login’] = True  用session存值
b)	is_login = request.session.get(‘is_login’,None)  获取session的值
c)	del request.session[‘is_login’]	销毁session
d)	settings.py中设置 SESSION_COOKE_AGE=10设置session10秒钟后过期自动销毁
	i.	SESSION_EXPIRE_AT_BROWSER_CLOSE 设置session是否随着浏览器关闭而销毁

4. Cooke

response = render_to_response(‘index.html’,ret)
response.set_cookie(‘key’, ‘value’)   #设置cooke
print request.COOKIES   #获取cookie
request.COOKIES.get(‘page_num’,10)

 

posted @ 2017-01-08 16:45  taibai  阅读(104)  评论(0编辑  收藏  举报