zoukankan      html  css  js  c++  java
  • django queryset高级用法

    https://docs.djangoproject.com/en/dev/ref/models/expressions/

    from django.db.models import Count, F, Value
    from django.db.models.functions import Length, Upper
    
    # Find companies that have more employees than chairs.
    Company.objects.filter(num_employees__gt=F('num_chairs'))
    
    # Find companies that have at least twice as many employees
    # as chairs. Both the querysets below are equivalent.
    Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
    Company.objects.filter(
        num_employees__gt=F('num_chairs') + F('num_chairs'))
    
    # How many chairs are needed for each company to seat all employees?
    >>> company = Company.objects.filter(
    ...    num_employees__gt=F('num_chairs')).annotate(
    ...    chairs_needed=F('num_employees') - F('num_chairs')).first()
    >>> company.num_employees
    120
    >>> company.num_chairs
    50
    >>> company.chairs_needed
    70
    
    # Create a new company using expressions.
    >>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
    # Be sure to refresh it if you need to access the field.
    >>> company.refresh_from_db()
    >>> company.ticker
    'GOOG'
    
    # Annotate models with an aggregated value. Both forms
    # below are equivalent.
    Company.objects.annotate(num_products=Count('products'))
    Company.objects.annotate(num_products=Count(F('products')))
    
    # Aggregates can contain complex computations also
    Company.objects.annotate(num_offerings=Count(F('products') + F('services')))
    
    # Expressions can also be used in order_by(), either directly
    Company.objects.order_by(Length('name').asc())
    Company.objects.order_by(Length('name').desc())
    # or using the double underscore lookup syntax.
    from django.db.models import CharField
    from django.db.models.functions import Length
    CharField.register_lookup(Length)
    Company.objects.order_by('name__length')
    
    # Boolean expression can be used directly in filters.
    from django.db.models import Exists
    Company.objects.filter(
        Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
    )
  • 相关阅读:
    C++范围解析运算符::的使用
    C程序的内存布局
    ARM中LDR伪指令与LDR加载指令
    每天一个linux命令(12):more命令
    C++ explicit关键字
    C++内联函数详解
    C++友元详解
    C++ new操作符详解
    CDN技术详解笔记
    字符串匹配(KMP 算法 含代码)
  • 原文地址:https://www.cnblogs.com/lxgbky/p/13826044.html
Copyright © 2011-2022 走看看