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')
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.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With