Django常用的查询命令

反向查找

questionchoice的外键。通过下面的方式question查找对应的choice:

# choice_set是默认的名称
question.choice_set.get

F()表达式

1、是什么?

F() 对象表示一个模型字段或注解列的值。它使得引用模型字段的值和使用它们执行数据库操作成为可能,而不需要将它们从数据库中拉到 Python 内存中。

取而代之的是,Django 使用 F() 对象来生成一个 SQL 表达式,在数据库层面描述所需的操作。

2、作用

  1. 让数据库,而不是 Python 来完成工作
  2. 减少某些操作所需的查询次数
  3. 避免竞争状态

3、使用场景

1)更新字段

from django.db.models import F

reporter = Reporters.objects.get(name='TIntin')
reporter = stories_filed = F('stories_filed') + 1
repotter.save()

2)用于QuerySets

reporter = Reporters.objects.filter(name='Tintin')
reporter.update(stories_filed=F('stories_filed') + 1)
Reporter.objects.all().update(stories_filed=F('stories_filed') + 1)

3)在过滤器中使用

要怎么做才能将模型字段值与同一模型中的另一字段做比较呢?F 就提供了这个功能

from django.db.models import F

Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks'))

4)与注解一起使用

动态创建某个model上没有定义的字段

company = Company.objects.annotate(
    chairs_needed=F('num_employees') - F('num_chairs'))

5)使用F()队空值进行排序

使用 F()Expression.asc()esc() 的关键词参数 nulls_firstnulls_last 来控制字段的空值的排序。默认情况下,排序取决于你的数据库。

例如,在已经联系过的公司之后,对尚未联系过的公司进行排序(last_contacted 为空)

from django.db.models import F
Company.objects.order_by(F('last_contacted').desc(nulls_last=True))

4、注意事项

1)F() 赋值在 Model.save() 之后持续存在

reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()

# reporter.refresh_from_db() 避免这种情况的发生
reporter.name = 'Tintin Jr.'
reporter.save()

stories_filed会加2。

2)不支持 output_field

需要使用ExpressionWrapper来包装表达式

from django.db.models import DateTimeField, ExpressionWrapper, F

Ticket.objects.annotate(
    expires=ExpressionWrapper(
        F('active_at') + F('duration'), output_field=DateTimeField()))

3)关系字段

当引用关系字段如 ForeignKey 时,F() 返回主键值而不是模型实例

>> car = Company.objects.annotate(built_by=F('manufacturer'))[0]
>> car.manufacturer
<Manufacturer: Toyota>
>> car.built_by
3
posted @ 2021-03-05 13:14  zhengyuanyuan  阅读(201)  评论(0)    收藏  举报