models之ManytoMany自关联
from django.shortcuts import render,HttpResponse,redirect from app01 import models # Create your views here. def test(request): # models.UserInfo.objects.create(username='zhangsan',password='123',name='张三',gender='1') # models.UserInfo.objects.create(username='lisi',password='123',name='李四',gender='1') # models.UserInfo.objects.create(username='wangwu',password='123',name='王五',gender='1') # models.UserInfo.objects.create(username='xiaohong',password='123',name='小红',gender='2') # models.UserInfo.objects.create(username='xiaobai',password='123',name='小白',gender='2') # models.UserInfo.objects.create(username='xiaolan',password='123',name='小兰',gender='2') # zhangsan=models.UserInfo.objects.filter(id=1).first() # # print(zhangsan) # result=zhangsan.girls.all() # print(result) # for i in result: # print(i.g.name) zhangsan=models.UserInfo.objects.filter(id=1).first() v=zhangsan.m.all() print(v) xiaobai=models.UserInfo.objects.filter(id=5).first() result=xiaobai.userinfo_set.all() print(result) return HttpResponse('ssss')
from django.db import models # Create your models here. class UserInfo(models.Model): name=models.CharField(max_length=32) username=models.CharField(max_length=32) password=models.CharField(max_length=32) gender_choice=( (1,'男'), (2,'女'), ) gender=models.IntegerField(choices=gender_choice) m = models.ManyToManyField('UserInfo') # class U2U(models.Model): # b=models.ForeignKey('UserInfo',on_delete=models.PROTECT,related_name='girls') # g=models.ForeignKey('UserInfo',on_delete=models.PROTECT,related_name='boys')
ORM中queryset对象之后返回数据类型:
- values返回是字典列表;
- values_list返回的是元组列表,
-
values_list加上
flat=True
之后返回值列表 - .first可以取queryset对象
view.py利用装饰器对页面做session验证:
from functools import wraps def check_login(f): @wraps(f) def inner(request): if request.session.get('is_login'): return f(request) else: return redirect('/login.html/') return inner