Django - 查询给出一列不等于同一模型中的另一列的行

Var*_*rma 9 python django django-models django-queryset

我的模型有3个字段

class Table(models.Model):
    in_time = models.DateTimeField(null=True, blank=True) 
    actual_time = models.DateTimeField(null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

我想以这种方式获取结果:

select * from Table where in_time > '2013-12-31 00:00:00' and in_time != actual_time
Run Code Online (Sandbox Code Playgroud)

所以任何人都可以帮我完成这个

result = Table.objects.filter(in_time__gte = '2013-12-31 00:00:00')
Run Code Online (Sandbox Code Playgroud)

Pro*_*e85 15

你在寻找的是:

https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

解决方案:

from django.db.models import F
from datetime import datetime

min_date = datetime(2013,12,31)
result = Table.objects.filter(in_time__gte=min_date).\
exclude(in_time__eq=F('actual_time'))
Run Code Online (Sandbox Code Playgroud)


ndp*_*dpu 6

使用Qwith~运算符来构建否定 (NOT) 查询:

import datetime
from django.db.models import Q, F

Table.objects.filter(~Q(in_time=F('actual_time')),
                     in_time__gt=datetime.datetime(2013,12,31))
Run Code Online (Sandbox Code Playgroud)

F引用同一模型上的字段:

Django 提供了 F 表达式来允许这样的比较。F() 的实例充当对查询中模型字段的引用。然后可以在查询过滤器中使用这些引用来比较同一模型实例上两个不同字段的值。