--- query.py.orig	2008-01-19 14:37:37.000000000 +0100
+++ query.py	2008-02-03 13:21:34.000000000 +0100
@@ -186,8 +186,14 @@
         extra_select = self._select.items()
 
         cursor = connection.cursor()
-        cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
-
+        select, sql, params = self._get_sql_clause()
+        if self._distinct == False:
+            distinct = ""
+        elif self._distinct == True:
+            distinct = "DISTINCT "
+        else:
+            distinct = "DISTINCT ON (%s) " % (','.join(self._distinct))
+        cursor.execute("SELECT " + distinct + ",".join(select) + sql, params)
         fill_cache = self._select_related
         fields = self.model._meta.fields
         index_end = len(fields)
@@ -236,11 +242,29 @@
 
         cursor = connection.cursor()
         if self._distinct:
-            id_col = "%s.%s" % (connection.ops.quote_name(self.model._meta.db_table),
+            table, column = None, None
+            if self._distinct == True:
+                # Simple DISTINCT  query
+                id_col = "%s.%s" % (
+                    connection.ops.quote_name(self.model._meta.db_table),
                     connection.ops.quote_name(self.model._meta.pk.column))
-            cursor.execute("SELECT COUNT(DISTINCT(%s))" % id_col + sql, params)
-        else:
-            cursor.execute("SELECT COUNT(*)" + sql, params)
+            elif len(self._distinct) == 1:
+                # DISTINCT ON query with single field
+                id_col = self._distinct[0]
+            else:
+                # DISTINCT ON with multiple fields: emulate SELECT COUNT
+                id_col = "%s.%s" % (
+                    connection.ops.quote_name(self.model._meta.db_table),
+                    connection.ops.quote_name(self.model._meta.pk.column))
+                cursor.execute("SELECT DISTINCT ON (%s) %s " % (
+                        ','.join(self._distinct), id_col) + sql, params)
+                # Don't have to correct the result for OFFSET and LIMIT as
+                # we performed an ordinary query.
+                return(len(cursor.fetchall()))
+
+            cursor.execute("SELECT COUNT(DISTINCT(%s))" % id_col + sql,
+                           params)
+
         count = cursor.fetchone()[0]
 
         # Apply any offset and limit constraints manually, since using LIMIT or
@@ -421,8 +445,19 @@
                 "Cannot reorder a query once a slice has been taken."
         return self._clone(_order_by=field_names)
 
-    def distinct(self, true_or_false=True):
+    def distinct(self, true_or_false=True, on_fields=None):
         "Returns a new QuerySet instance with '_distinct' modified."
+        if on_fields:
+            if type(on_fields) == type(''):
+                on_fields = (on_fields,)
+            # Quote the field names
+            on_fields = [
+                connection.ops.quote_name(len(p) == 1
+                                          and self.model._meta.db_table
+                                          or p[0])
+                + '.' + connection.ops.quote_name(p[-1])
+                for p in [f.split('.',1) for f in on_fields]]
+            return self._clone(_distinct=on_fields)
         return self._clone(_distinct=true_or_false)
 
     def extra(self, select=None, where=None, params=None, tables=None):
@@ -462,6 +497,9 @@
         assert self._limit is None and self._offset is None \
             and other._limit is None and other._offset is None, \
             "Cannot combine queries once a slice has been taken."
+        # CHECKME: for DISTINCT ON queries this will always return false
+        # unless both field sets are identical. I don't know if this is
+        # correct, if so the error message may have to be adapted.
         assert self._distinct == other._distinct, \
             "Cannot combine a unique query with a non-unique query"
         #  use 'other's order by
@@ -617,7 +655,13 @@
             field_names.extend([f[0] for f in extra_select])
 
         cursor = connection.cursor()
-        cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
+        if self._distinct == False:
+            distinct = ""
+        elif self._distinct == True:
+            distinct = "DISTINCT "
+        else:
+            distinct = "DISTINCT ON (%s) " % (','.join(self._distinct))
+        cursor.execute("SELECT " + distinct + ",".join(select) + sql, params)
 
         has_resolve_columns = hasattr(self, 'resolve_columns')
         while 1:
