title: Querying Colorspace in a Database
body: <p>I'm using Django and have a MySQL database filled with arbitrary RGB colors. The RGB values are stored as Integers.</p>
  
  <pre><code>| Name  | R | G | B |
  +-------+---+---+---+
  | Green | 0 |255| 0 |
  | Cyan  | 0 |255|255|
  | ...   | . | . | . |
  | Foo   |123| 45| 2 |
  | ...   | . | . | . |
  </code></pre>
  
  <p>Given an arbitrary RGB value <code>(a,b,c)</code> I want to calculate what colors in the database are "close to" <code>(a,b,c)</code>. I'll predefine what "close to" means in my query but for now let's call it <code>x</code>.</p>
  
  <p>You can think of the RGB color space as a three dimensional space with colors as points in that space. So <code>(a,b,c)</code> and <code>x</code> define a sphere in that space with a center point <code>(a,b,c)</code> and radius <code>x</code>.</p>
  
  <p>Pythagorus tells us that the following is true for all of the points within this sphere:</p>
  
  <pre><code>(R-a)**2 + (G-b)**2 + (B-c)**2 &lt;= x**2
  </code></pre>
  
  <p>I would like to translate this into a valid Django Query. And, failing that, a MySQL query.</p>
  
  <p>I'm no MySQL expert but I have some suspicions that the Django Query syntax may be very limiting in this context. Would writing a raw SQL query be the way to go here? Would it be better because the code would be more clear? Could it actually be faster/more efficient?</p>
  
  <hr>
  
  <p>Django Color Model looks like:</p>
  
  <pre><code>class Color(models.Model):
      name = models.CharField(max_length=32)
      r = models.IntegerField()
      g = models.IntegerField()
      b = models.IntegerField()
  </code></pre>
  
  <p>An example query:</p>
  
  <pre><code>c = (234, 23, 45)
  x = 25
  
  nearby_colors = Color.objects.filter(....) # Awesome-sauce
  </code></pre>