Comparing Object Fields with Django's ORM

前端 未结 1 1536
轻奢々
轻奢々 2021-01-29 00:29

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 Dj

相关标签:
1条回答
  • 2021-01-29 01:11

    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`
    >>> 
    
    0 讨论(0)
提交回复
热议问题