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))
    )
  • 相关阅读:
    Source Insight 安装使用
    size_t和ssize_t
    jquery ui autoComplete自动完成
    一个php类 Autoloader
    php register_shutdown_function
    mysql concat和group_concat
    nginx反向代理
    6.关于QT中的内存管理,动态的制作,动态库的调用,静态库的制作
    Sublime Text2 按shift键选择不了的问题
    javascript--瀑布流
  • 原文地址:https://www.cnblogs.com/lxgbky/p/13826044.html
Copyright © 2011-2022 走看看