Cerin
Cerin

Reputation: 64769

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, which would have the SQL equivalent of:

SELECT a.id
FROM mytable a
LEFT OUTER JOIN myothertable b ON b.id = a.other_id AND a.val < b.someval

Clearly, I can't use the normal filter() notation, since the RHS assumes the value is a literal, not an object/attribute name. e.g.

MyTable.objects.filter(val__lt=other__someval)

Upvotes: 1

Views: 1803

Answers (1)

dting
dting

Reputation: 39287

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`
>>> 

Upvotes: 4

Related Questions