Skip to content Skip to sidebar Skip to footer

Comparing Object Fields With Django's ORM

Is comparing columns in different tables using less-than/greater-than operators supported in Django's ORM? For example, I'm trying to compare two object fields in a Django query, w

Solution 1:

S.Lott's answer is the way to go. Here's an example of using F:

class ModelA(models.Model):
    val = IntegerField()
    model_b = ForeignKey('ModelB')

class ModelB(models.Model):
    val = IntegerField()


>>> from django.db.models import F
>>> ModelA.objects.filter(val__lt=F('model_b__val'))
>>> print qs.query
SELECT `test_modela`.`id`, `test_modela`.`val`, `test_modela`.`model_b_id` FROM `test_modela` INNER JOIN `test_modelb` ON (`test_modela`.`model_b_id` = `test_modelb`.`id`) WHERE `test_modela`.`val` <  `test_modelb`.`val`
>>> 

Post a Comment for "Comparing Object Fields With Django's ORM"