| 536 | def count(self): |
| 537 | "Performs a SELECT COUNT() and returns the number of records as an integer." |
| 538 | counter = self._clone() |
| 539 | counter._order_by = () |
| 540 | counter._offset = None |
| 541 | counter._limit = None |
| 542 | counter._select_related = False |
| 543 | select, sql, params = counter._get_sql_clause() |
| 544 | cursor = connection.cursor() |
| 545 | |
| 546 | # self._fields is a list of field names to fetch. |
| 547 | if self._fields: |
| 548 | columns = [self.model._meta.get_field(f, many_to_many=False).column for f in self._fields] |
| 549 | column_names = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns] |
| 550 | select_spec = ', '.join(column_names) |
| 551 | else: # Default to id_col |
| 552 | select_spec = "%s.%s" % (backend.quote_name(self.model._meta.db_table), |
| 553 | backend.quote_name(self.model._meta.pk.column)) |
| 554 | |
| 555 | if self._distinct: |
| 556 | cursor.execute("SELECT COUNT(DISTINCT(%s))" % select_spec + sql, params) |
| 557 | else: |
| 558 | cursor.execute("SELECT COUNT(*)" + sql, params) |
| 559 | return cursor.fetchone()[0] |
| 560 | |