Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 653
Varun Verma Avatar asked Jan 09 '14 14:01

Varun Verma


2 Answers

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.

like image 99
ndpu Avatar answered Nov 06 '22 23:11

ndpu


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'))
like image 39
ProfHase85 Avatar answered Nov 07 '22 00:11

ProfHase85