Note that there are some explanatory texts on larger screens.

plurals
  1. POColumn comparison in Django queries
    text
    copied!<p>I have a following model:</p> <pre><code>class Car(models.Model): make = models.CharField(max_length=40) mileage_limit = models.IntegerField() mileage = models.IntegerField() </code></pre> <p>I want to select all cars where mileage is less than mileage_limit, so in SQL it would be something like:</p> <pre><code>select * from car where mileage &lt; mileage_limit; </code></pre> <p>Using Q object in Django, I know I can compare columns with any value/object, e.g. if I wanted to get cars that have mileage say less than 100,000 it would be something like:</p> <pre><code>cars = Car.objects.filter(Q(mileage__lt=100000)) </code></pre> <p>Instead of a fixed value I would like to use the column name (in my case it is mileage_limit). So I would like to be able to do something like:</p> <pre><code>cars = Car.objects.filter(Q(mileage__lt=mileage_limit)) </code></pre> <p>However this results in an error, since it is expecting a value/object, not a column name. Is there a way to compare two columns using Q object? I feel like it would be a very commonly used feature and there should be an easy way to do this, however couldn't find anything about it in the documentation.</p> <p><em>Note: this is a simplified example, for which the use of Q object might seam to be unnecessary. However the real model has many more columns, and the real query is more complex, that's why I am using Q. Here in this question I just wanted to figure out specifically how to compare columns using Q.</em></p> <p><b>EDIT</b></p> <p>Apparently after release of Django 1.1 it would be possible to do the following:</p> <pre><code>cars = Car.objects.filter(mileage__lt=F('mileage_limit')) </code></pre> <p>Still not sure if F is supposed to work together with Q like this:</p> <pre><code>cars = Car.objects.filter(Q(mileage__lt=F('mileage_limit'))) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload