Varun Verma
Varun Verma

Reputation: 501

Django - query for to give rows where one column Not equals to another column in same model

My model have 3 fields

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

Upvotes: 16

Views: 9973

Answers (2)

ndpu
ndpu

Reputation: 22561

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

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:

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.

Upvotes: 8

ProfHase85
ProfHase85

Reputation: 12173

What you are searching for is:

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

Upvotes: 20

Related Questions