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')))
    
  • 相关阅读:
    golang 数组的一些自问自答
    这辈子研究 我的闪存
    我写的诗 爱你等于爱自己
    个人创业相关资料 创业与投资文章
    公司商业模式案例讲座 公司商业模式
    1、开篇:公司的价值 企业管理线细化系列文章
    visual studio 2022 企业版 下载
    芝奇DDR4 5066Hz 8Gx2内存闲置 个人闲置物品买卖
    INF: How SQL Server Compares Strings with Trailing Spaces
    虚拟 DOM 到底是什么?
  • 原文地址:https://www.cnblogs.com/wspblog/p/6491806.html
Copyright © 2011-2022 走看看