django模板

模板查找顺序:
查找顺序 
setting.py(INSTALL_APPS)顺序查找(APP)templates目录下的所有模板名字的字符串匹配(先全局,再局部),一旦匹配就不会再找

查找路径 
完整路径:$APP/templates/user/login.html(从templates路径下算起)
from django.shortcuts import render
from django.views import View
from django.views.generic.base import TemplateView

class LoginView(View)
    def get(self, request, *args, **kwargs):
    retrun render(request, 'test/login.html')

class LoginView(TemplateView):
    template_name = "test/login.html"

django 模型

新建字段:

常用模型字段类型

注意:默认情况下Django会给每个模型添加下面这个字段id = models.AutoField(primary_key=True),如果Django看到你显式地设置了Field.primary_key, 就不会自动添加 id 列,每个模型只有一个字段指定primary_key=True

数据库迁移

迁移是Django同步您对模型所做更改(添加字段,删除模型等) 到您的数据库模式的方式
命令: 
pyton manage.py [COMMAND]

migrate,负责应用和取消应用迁移。
makemigrations, 负责基于你的模型修改创建一个新的迁移
sqlmigrate, 展示迁移的sql语句
showmigrations,其中列出了项目的迁移及其状态。
##迁移指定app,生成迁移文件
[root@test-01 cmdb-14]# python manage.py makemigrations webanalysis
Migrations for 'webanalysis':
  webanalysis/migrations/0002_idc.py
    - Create model Idc

##展示迁移的sql语句
[root@test-01 cmdb-14]# python manage.py sqlmigrate webanalysis 0002

##数据迁移
[root@test-01 cmdb-14]# python manage.py migrate webanalysis
Operations to perform:
  Apply all migrations: webanalysis
Running migrations:
  Applying webanalysis.0002_idc... OK

注意:创建对象使用save(),或者使用create()方法

模型与数据库不一致的处理办法:

误删除迁移表,再次进行migration提示该表已存在

##误操作删除迁移表
 select * from django_migrations;
14 | dashboard    | 0001_initial                             | 2018-10-28 03:42:04
 delete from django_migrations where id = 14; 

##再次执行迁移
python manage.py migrate dashboard
#报错:django.db.utils.OperationalError: (1050, "Table 'dashboard_idc' already exists")

##基于版本之间同步 强制执行 不执行数据库操作
python manage.py migrate dashboard --fake

模型里面有,数据库不一致
##先保证model.py与数据库一致
##删除迁移文件app/migrations/0001xxx
##删除数据库django_migrations下的迁移记录
##重新同步makemigrations migrate

delete from django_migrations where id >= 15;
python manage.py makemigrations dashboard
python manage.py migrate dashboard

执行查询

##导入模型

python manage.py shell
from [APP].models import [MODEL]
from django.contrib.auth.models import User,Group

>>> User.objects.all()
>>> User.objects.filter(name='xiaopf1').delete()
>>> User.objects.exclude(name='xiaopf1').update(name='xiaopf2')
>>> User.objects.filter(age__gt=10)  #age>10 双下划线必须得加上
>>> User.objects.filter(age__gte=10) #age>=10
>>> User.objects.filter(age__lte=10)
>>> User.objects.filter(age__lt=10)
>>> User.objects.filter(name__contains='xiaopf')
>>> User.objects.filter(name__endswith='1')
>>> User.objects.filter(age__in=[10,11,12]).count()
>>> User.objects.filter(age__in=[10,11,12]).values('name','id')
>>> User.objects.order_by('age')
>>> User.objects.order_by('-age')   #降序
>>> User.objects.order_by('age')[0]
>>> User.objects.order_by('age')[:3]
>>> User.objects.filter(name='xiaopf').update(addr='jieshou')
>>> User.objects.filter(name='xiaopf9').delete()

新增数据

##filter其他查询方法 ###q.exclude/filter(body_text__icontains="food") exact “精确”匹配 iexact 大小写不敏感的匹配 contains 大小写敏感的包含指定字符串 icontains 大小写不敏感的包含指定字符串 startswith, endswith 以指字字符串开头或结尾 istartswith, iendswith in 在给定的列表内

##关系联系符 gt 大于 gte 大于或等于 lt 小于 lte 小于或等于 range 在指定范围内

filter()和get()区别 filter() 始终返回一个查询集,除非只有一个 只有一个对象满足你的查询,使用one_entry = Entry.objects.get(pk=1) 可以对get()使用任何查询表达式,和filter()一样 如果没有结果满足查询(单条),get()将引发一个Objects.DoesNotExist异常 如果多条满足get()查询条件,引发MultipleObjectsReturned异常 注意:使用from django.core.exceptions import ObjectDoesNotExist,MultipleObjectsReturned导入异常

序列化对象 将对象转换为可读的json格式serializers

from django.contrib.auth.models import User,Group
from django.core import serializers

class GroupListView(View):
    '''
    获取用组列表
    '''
    def get(self, request, *args, **kwargs):
        queryset = Group.objects.all()
        return HttpResponse(serializers.serialize("json", queryset), content_type="application/json")

django 模型关系

关系数据库的威力体现在表之间的相互关联。 Django 提供了三种最常见的数据库关系:多对一(many-to-one),多对多(many-to-many),一对一(one-to-one)

多对一 Django 使用 django.db.models.ForeignKey 定义多对一关系,ForeignKey关联的模型是一,Foreignkey所在的模型是多

简单的例子: 比如,一辆Car有一个Manufacturer ,但是一个Manufacturer 生产很多汽车(Car),每一辆Car 只能有一个Manufacturer

class Car(models.Model):
    name = models.CharField('名字',max_length=50,null=False,default='')
    manufacturer=models.ForeignKey(Manufacturer)

class Manufacturer(models.Model):
    name = models.CharField('名字',max_length=50,null=False,default='')

迁移,生产数据库

验证: 先有制造商,再有车吧,所以先新建制造商的对象 In [1]: from dashboard.models import Car,Manufacturer

In [2]: m1 = Manufacturer.objects.create(name='宝马')

In [3]: x1 = Car()

In [4]: x1.manufacturer = m1

In [5]: x1.name = 'x1'

In [6]: x1.save()

##正向查询,通过小汽车查询供应商(多对一) In [8]: x1 = Car.objects.get(name='x1')

In [9]: x1.manufacturer.name
Out[9]: '宝马'

##反向查询,通过供应商查询小汽车(一对多) In [10]: m = Manufacturer.objects.get(name='宝马')

In [11]: m.car_set.all()
Out[11]: <QuerySet [<Car: Car object>]>

##修改小汽车关联供应商对象 In [50]: m1.name
Out[50]: '宝马'

In [51]: m1.car_set.add(x1)

In [52]: x1.manufacturer.name
Out[52]: '宝马'

In [53]: x1.name
Out[53]: 'x1'

删除: In [54]: x1.delete()
Out[54]: (1, {'dashboard.Car': 1}) 注意:删除对象的时候先查看是否有关联,再删除数据,因为如果删除供应商,与之关联的小汽车也将被删除。

修改: In [52]: x1.manufacturer.name
Out[52]: '宝马'

In [53]: x1.name
Out[53]: 'x1'

In [54]: x1.delete()
Out[54]: (1, {'dashboard.Car': 1})

In [55]: m2 = Manufacturer.objects.get(name='奥迪')

In [56]: x1.manufacturer = m2

In [57]: x1.name
Out[57]: 'x1'

In [58]: x1.manufacturer.name
Out[58]: '奥迪'

多对多 ManyToManyField,其中一个models定义就行了,在哪个模型中定义并不重要 实例: 一个组对应多个人,一个人对应多个组

新增:
In [61]: from django.contrib.auth.models import Group,User
In [4]: Group.objects.create(name='admin')
In [4]: u = User.objects.get(username='user1')                                                                                       

In [5]: g1 = Group.objects.get(name='admin')     

个人添加到组

In [6]: u.groups.add(g1)                                                                                                             

In [7]: u.groups.all()                                                                                                               
Out[7]: <QuerySet [<Group: admin>]>

组添加人:

In [11]: u2 = User.objects.get(username='user2')                                                                                     

In [12]: g1.user_set.add(u2)                                                                                                         

In [13]: g1.user_set.all()                                                                                                           
Out[13]: <QuerySet [<User: user1>, <User: user2>]>

个人删除组:

In [19]: u2.groups.all()                                                                                                             
Out[19]: <QuerySet [<Group: admin>]>

In [20]: u2.groups.remove(g1)                                                                                                        

In [21]: u2.groups.all()                                                                                                             
Out[21]: <QuerySet []>

组删除个人:

In [26]: g1.user_set.all()                                                                                                           
Out[26]: <QuerySet [<User: user2>]>

In [27]: g1.user_set.remove(u2)                                                                                                      

In [28]: g1.user_set.all()                                                                                                           
Out[28]: <QuerySet []>

彻底清空: 组:

In [48]: g2.user_set.all()                                                                                                           
Out[48]: <QuerySet [<User: user1>, <User: user2>]>

In [49]:                                                                                                                             

In [49]: g2.user_set.clear()                                                                                                         

In [50]: g2.user_set.all()                                                                                                           
Out[50]: <QuerySet []>

个人:
In [57]: u.groups.all()                                                                                                              
Out[57]: <QuerySet [<Group: wo>, <Group: admin>]>

In [58]: u.groups.clear()                                                                                                            

In [59]: u.groups.all()                                                                                                              
Out[59]: <QuerySet []>

重点:

使用serializers序列化对象为Json格式
from django.core import serializers

class GroupListView(View):
    def get(self, request, *args, **kwargs):
        queryset = Group.objects.all()
        return HttpResponse(serializers.serialize("json", queryset), content_type="application/json")

Queryset对象或对象集不存在捕捉错误

from django.http import HttpResponse,Http404
from django.core.exceptions import ObjectDoesNotExist,MultipleObjectsReturned

class GroupUserView(View):
    def get_group_obj(self):
        try:
            groupobj = Group.objects.get(name=self.request.GET.get('name'))
        except Group.DoesNotExist:
            raise Http404
        except Group.MultipleObjectsReturned:
            raise Http404
        
        return groupobj
class GroupMembers(View):
    '''
    获取用户组下的成员列表,参数为组名
    '''
    def get_group_members(self):
        group_name = self.request.GET.get('name')
        try:
            groupobj = Group.objects.get(name=group_name)
        except Group.DoesNotExist:
            raise Http404
        except Group.MultipleObjectsReturned:
            raise Http404
        get_group_members = groupobj.user_set.all()
        return get_group_members

    def get(self,request,*args,**kwargs):
        queryset = self.get_group_members()
        return HttpResponse(serializers.serialize('json', queryset), content_type="application/json")
class UserGroupList(View):
    '''
    获取用户组列表,参数为用户名
    '''
    def get_user_obj(self):
        userobj = self.get_user()
        return userobj.groups.all()
    def get_user(self):
        try:
            userobj = User.objects.get(username=self.request.GET.get('username'))
        except User.DoesNotExist:
            raise Http404
        except User.MultipleObjectsReturned:
            raise Http404
        return userobj

    def get(self,request,*args,**kwargs):
        queryset = self.get_user_obj()
        return HttpResponse(serializers.serialize('json', queryset), content_type="application/json")
from django.http import QueryDict

<QueryDict: {'username': ['user3'], 'groupname': ['admin']}>
class GroupManage(View):
    def get_group(self):
        print(QueryDict(self.request.body))
        try:
            groupobj = Group.objects.get(name=QueryDict(self.request.body).get('groupname'))
        except Group.DoesNotExist:
            raise Http404
        except Group.MultipleObjectsReturned:
            raise Http404
        return groupobj

    def user_group(self):
        try:
            userobj = User.objects.get(username=QueryDict(self.request.body).get('username'))
        except User.DoesNotExist:
            raise Http404
        except User.MultipleObjectsReturned:
            raise Http404
        return userobj

    def delete(self,request,*args,**kwargs):
        '''
        将用户从用户组里删除
        '''
        userobj = self.user_group()
        groupobj = self.get_group()
        groupobj.user_set.remove(userobj)
        return HttpResponse('用户已从用户组里删除')

    def put(self,request,*args,**kwargs):
        '''
        将用户添加至用户组里
        '''
        userobj = self.user_group()
        groupobj = self.get_group()
        groupobj.user_set.add(userobj)

        return HttpResponse('用户已添加至用户组')
验证:
In [46]: import requests
In [42]: data={'username':'user3',"groupname":'admin'}                                                                               

In [43]: url="http://192.168.1.16:8000/dashboard/usergroupmanage/"                                                                   

In [44]: r = requests.put(url,data=data)                                                                                                  

In [45]: r.content.decode('utf8')                                                                                                    
Out[45]: '用户已添加至用户组'

In [73]: r = requests.delete(url,data=data)                                                                                          

In [74]: r.content.decode('utf8')                                                                                                    
Out[74]: '用户已从用户组里删除