• 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')))
    
  • 相关阅读:
    扩展Dijkstra
    CodeForces 1396E. Distance Matching
    大联盟2
    整式乘除法
    美国数学会众多教授推荐的本科&研究生代数几何经典书籍教材清单
    算法题——立方体的体对角线穿过多少个正方体?
    导数练习题
    导数压轴题
    集合
    著名数学家Ky Fan的故事
  • 原文地址:https://www.cnblogs.com/wspblog/p/6491806.html
Copyright © 2020-2023  润新知