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))
    )
  • 相关阅读:
    如何用StatSVN统计SVN服务器某项目的代码量
    探秘JVM的底层奥秘
    SpingMVC流程图
    NioCopy文件
    我的angularjs源码学习之旅3——脏检测与数据双向绑定
    我的angularjs源码学习之旅2——依赖注入
    我的angularjs源码学习之旅1——初识angularjs
    IE兼容性问题汇总【持续更新中】
    nodejs学习笔记四——express-session
    我理解的this
  • 原文地址:https://www.cnblogs.com/lxgbky/p/13826044.html
Copyright © 2011-2022 走看看