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

时间:2022-02-28 15:45:20

My model have 3 fields

我的模型有3个字段

class Table(models.Model):
    in_time = models.DateTimeField(null=True, blank=True) 
    actual_time = models.DateTimeField(null=True, blank=True)

i want to fetch results in this way :

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

select * from Table where in_time > '2013-12-31 00:00:00' and in_time != actual_time

So can anyone help me in completing this

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

result = Table.objects.filter(in_time__gte = '2013-12-31 00:00:00')

2 个解决方案

#1


11  

What you are searching for is:

你在寻找的是:

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

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

SOLUTION:

解:

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'))

#2


4  

Use Q with ~ operator to build negated (NOT) query:

使用Q和〜运算符构建否定(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))

And F to reference fields on same model:

和F引用相同型号的字段:

Django provides F expressions to allow such comparisons. Instances of F() act as a reference to a model field within a query. These references can then be used in query filters to compare the values of two different fields on the same model instance.

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

#1


11  

What you are searching for is:

你在寻找的是:

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

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

SOLUTION:

解:

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'))

#2


4  

Use Q with ~ operator to build negated (NOT) query:

使用Q和〜运算符构建否定(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))

And F to reference fields on same model:

和F引用相同型号的字段:

Django provides F expressions to allow such comparisons. Instances of F() act as a reference to a model field within a query. These references can then be used in query filters to compare the values of two different fields on the same model instance.

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