diff --unified -r a/django/db/backends/postgresql/operations.py b/django/db/backends/postgresql/operations.py
--- a/django/db/backends/postgresql/operations.py	2010-04-29 02:22:50.000000000 +0100
+++ b/django/db/backends/postgresql/operations.py	2010-05-24 15:30:28.020590238 +0100
@@ -54,7 +54,8 @@
         return '%s'
 
     def last_insert_id(self, cursor, table_name, pk_name):
-        cursor.execute("SELECT CURRVAL('\"%s_%s_seq\"')" % (table_name, pk_name))
+        # Use pg_get_serial_sequence to get the underlying sequence name from the table name and column name (available since postgres 8)
+        cursor.execute("SELECT CURRVAL(pg_get_serial_sequence('%s','%s'))" % (table_name, pk_name))
         return cursor.fetchone()[0]
 
     def no_limit_value(self):
@@ -90,13 +91,17 @@
             for sequence_info in sequences:
                 table_name = sequence_info['table']
                 column_name = sequence_info['column']
-                if column_name and len(column_name) > 0:
-                    sequence_name = '%s_%s_seq' % (table_name, column_name)
-                else:
-                    sequence_name = '%s_id_seq' % table_name
-                sql.append("%s setval('%s', 1, false);" % \
+                if not (column_name and len(column_name) > 0):
+                    # This will be the case if it's an m2m using an intermediate table (see BaseDatabaseIntrospection.sequence_list)
+                    # - that function claims we don't need to reset the sequence if that's the case, although the code prior to the #8901
+                    # fix did reset it so I'm retaining resetting it - the pk will be id in those cases. (Note that sequence_reset_sql below also
+                    # seems to include resetting sequences of m2m with in intermediate table)
+                    column_name = 'id'
+                # Use pg_get_serial_sequence to get the underlying sequence name from the table name and column name (available since postgres 8)
+                sql.append("%s setval(pg_get_serial_sequence('%s','%s'), 1, false);" % \
                     (style.SQL_KEYWORD('SELECT'),
-                    style.SQL_FIELD(self.quote_name(sequence_name)))
+                    style.SQL_TABLE(table_name),
+                    style.SQL_FIELD(column_name))
                 )
             return sql
         else:
@@ -109,12 +114,15 @@
         for model in model_list:
             # Use `coalesce` to set the sequence for each model to the max pk value if there are records,
             # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true
-            # if there are records (as the max pk value is already in use), otherwise set it to false.
+            # if there are records (as the max pk value is already in use), otherwise set it to false.           
+            # Use pg_get_serial_sequence to get the underlying sequence name from the table name and column name (available since postgres 8)
+            
             for f in model._meta.local_fields:
                 if isinstance(f, models.AutoField):
-                    output.append("%s setval('%s', coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
+                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
                         (style.SQL_KEYWORD('SELECT'),
-                        style.SQL_FIELD(qn('%s_%s_seq' % (model._meta.db_table, f.column))),
+                        style.SQL_TABLE(model._meta.db_table),
+                        style.SQL_FIELD(f.column),
                         style.SQL_FIELD(qn(f.column)),
                         style.SQL_FIELD(qn(f.column)),
                         style.SQL_KEYWORD('IS NOT'),
@@ -123,9 +131,10 @@
                     break # Only one AutoField is allowed per model, so don't bother continuing.
             for f in model._meta.many_to_many:
                 if not f.rel.through:
-                    output.append("%s setval('%s', coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
+                    output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % \
                         (style.SQL_KEYWORD('SELECT'),
-                        style.SQL_FIELD(qn('%s_id_seq' % f.m2m_db_table())),
+                        style.SQL_TABLE(model._meta.db_table),
+                        style.SQL_FIELD('id'),
                         style.SQL_FIELD(qn('id')),
                         style.SQL_FIELD(qn('id')),
                         style.SQL_KEYWORD('IS NOT'),
diff --unified -r a/tests/regressiontests/backends/models.py b/tests/regressiontests/backends/models.py
--- a/tests/regressiontests/backends/models.py	2010-02-24 15:29:25.000000000 +0000
+++ b/tests/regressiontests/backends/models.py	2010-05-24 14:25:17.138194051 +0100
@@ -19,6 +19,15 @@
     year = models.PositiveIntegerField()
     day = models.CharField(max_length=9, blank=True)
     last_updated = models.DateTimeField()
+    
+class OtherRelatedThingTestBug8901(models.Model):
+    pass
+
+class VeryLongModelNameToTestBug8901ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ(models.Model):
+    class Meta:
+        verbose_name = 'TestBug8901' # Short verbose name or we hit issue in #8548 which we're not testing!
+    primary_key_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.AutoField(primary_key=True)
+    m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.ManyToManyField(OtherRelatedThingTestBug8901,blank=True)
 
 qn = connection.ops.quote_name
 
diff --unified -r a/tests/regressiontests/backends/tests.py b/tests/regressiontests/backends/tests.py
--- a/tests/regressiontests/backends/tests.py	2010-04-28 18:08:06.000000000 +0100
+++ b/tests/regressiontests/backends/tests.py	2010-05-24 15:20:20.326259674 +0100
@@ -7,6 +7,7 @@
 from django.db.backends.signals import connection_created
 from django.conf import settings
 from django.test import TestCase
+from django.core import management
 
 class Callproc(unittest.TestCase):
 
@@ -88,6 +89,26 @@
         self.assertRaises(Exception, cursor.executemany, query, [(1,2,3),])
         self.assertRaises(Exception, cursor.executemany, query, [(1,),])
 
+class PostgresqlSequenceNameLimitsTest(TestCase):
+    """Long primary keys and model names can result in a sequence name that's longer than
+    postgresql's limit of 63 characters so it truncates them. The backend needs to use the correct
+    sequence name in last_insert_id and other places, so check it is. Ref #8901."""
+    
+    def test_sequence_name_length_limits_create(self):
+        """Test creation of model with long name and long pk name doesn't error. Ref #8901"""
+        #import time
+        #time.sleep(1000)
+        models.VeryLongModelNameToTestBug8901ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
+
+    def test_sequence_name_length_limits_m2m(self):
+        """Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901"""
+        obj = models.VeryLongModelNameToTestBug8901ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
+        rel_obj = models.OtherRelatedThingTestBug8901.objects.create()
+        obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
+        
+    def test_sequence_name_length_limits_flush(self):
+        """Test management flush command with model with long name and long pk name doesn't error. Ref #8901"""
+        management.call_command('flush', verbosity=0, interactive=False)
 
 def connection_created_test(sender, **kwargs):
     print 'connection_created signal'
