zoukankan      html  css  js  c++  java
  • Python自动化之django orm之Q对象

    Python自动化之django orm之Q对象

    什么是Q对象?

    Encapsulates filters as objects that can then be combined logically (using& and |)

    关联查询

    Poll.objects.get(
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
        question__startswith='Who')
    

    AND AND

    def ceshi(request):
        from app01 import models
        from django.db.models import Q
        conn = Q()  # 大Q对象
        q1 = Q()  # 小Q对象
        
        # 下面都是或的关系
        q1.connector='OR'
        q1.children.append(('id', 1))
        q1.children.append(('id', 2))
        q1.children.append(('id', 3))
        
        #这个q2也是小Q
        q2 = Q()
        q2.connector = 'OR'
        q2.children.append(('name', 'wo'))
        conn.add(q1, 'AND')
        print(conn)
        print('------')
        conn.add(q2, 'AND')
        print(conn)
        print(q1)
        a = models.User.objects.filter(conn)
        print(a.values())
        return HttpResponse('ok')
    

    结果

    (AND: (OR: ('id', 1), ('id', 2), ('id', 3)))
    ------
    (AND: (OR: ('id', 1), ('id', 2), ('id', 3)), ('name', 'wo'))
    

    AND OR

    from django.shortcuts import render, HttpResponse
    from django.core.exceptions import NON_FIELD_ERRORS
    # Create your views here.
    
    from django import forms
    from django.forms import fields
    from django.forms import widgets
    
    class User(forms.Form):
        usertype = fields.ChoiceField(
            choices=[],
            widget=widgets.Select
    
        )
    
        def __init__(self,*args,**kwargs):
            super(User,self).__init__(*args,**kwargs)
            print(self.fields['usertype'])
            print(type(self.fields['usertype']))
        # print(dir())
    
    def ceshi(request):
        from app01 import models
        from django.db.models import Q
        conn = Q()
        q1 = Q()
        q1.connector='OR'
        q1.children.append(('id', 1))
        q1.children.append(('id', 2))
        q1.children.append(('id', 3))
    
        q2 = Q()
        q2.connector = 'OR'
        q2.children.append(('name', 'wo'))
        conn.add(q1, 'AND')
        print(conn)
        print('------')
        conn.add(q2, 'OR')
        print(conn)
    
        a = models.User.objects.filter(conn)
        return HttpResponse('ok')
    

    结果

    (AND: (OR: ('id', 1), ('id', 2), ('id', 3)))
    ------
    (OR: (AND: (OR: ('id', 1), ('id', 2), ('id', 3))), (OR: ('name', 'wo')))
    
  • 相关阅读:
    数组中删除指定某个元素(根据值删除,不是位置)
    gulp使用过程中走过的坑
    H5兼容不同屏幕尺寸
    jQuery基础——事件
    DOM的jquery操作(遍历)
    jquery的DOM操作(创建节点、插入节点、删除节点、复制节点、替换节点、包裹节点)
    gulp插件uncss的使用
    【代码总结-不定期更新】
    【Linux-学习笔记-不定期更新】
    【随时记录的一些东东-不定期更新】
  • 原文地址:https://www.cnblogs.com/wspblog/p/6491806.html
Copyright © 2011-2022 走看看