#12421: Foreign Key on Non-Primary Field fails due to lack of Index on Related
Field w/ MySQL
---------------------------------------------------+------------------------
          Reporter:  anonymous                     |         Owner:  nobody
            Status:  reopened                      |     Milestone:        
         Component:  Database layer (models, ORM)  |       Version:  SVN   
        Resolution:                                |      Keywords:        
             Stage:  Accepted                      |     Has_patch:  0     
        Needs_docs:  0                             |   Needs_tests:  0     
Needs_better_patch:  0                             |  
---------------------------------------------------+------------------------
Changes (by clouserw):

 * cc: [email protected] (added)
  * status:  closed => reopened
  * resolution:  worksforme =>

Comment:

 I can reproduce this with the following model:

 {{{
 from django.db import models

 class Item(models.Model):
     license = models.ForeignKey('License', to_field="name", null=True)

     class Meta:
         db_table = 'testo_item'

 class License(models.Model):
     name = models.PositiveIntegerField(db_index=True)

     class Meta:
         db_table = 'testo_license'
 }}}

 An important point to note is that I'm forcing InnoDB in my settings.py
 (which is the difference between this failing and not):
 {{{
 DATABASES = {
     'default': {
         ...
         'OPTIONS': {'init_command': 'SET storage_engine=InnoDB'},
     },
 }
 }}}

 At that point running sqlall will show you the order the commands are
 executed:

 {{{
 $ ./manage.py sqlall testo
 BEGIN;
 CREATE TABLE `testo_item` (
     `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
     `license_id` integer UNSIGNED
 )
 ;
 CREATE TABLE `testo_license` (
     `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
     `name` integer UNSIGNED
 )
 ;
 ALTER TABLE `testo_item` ADD CONSTRAINT `license_id_refs_name_a4fa988`
 FOREIGN KEY (`license_id`) REFERENCES `testo_license` (`name`);
 CREATE INDEX `testo_item_license_id` ON `testo_item` (`license_id`);
 CREATE INDEX `testo_license_name` ON `testo_license` (`name`);
 COMMIT;
 }}}

 Note that it's trying to add the foreign key before it creates the
 indexes.  Copying and pasting the above output will work fine, unless your
 default table type is InnoDB (or you can modify the CREATE TABLE
 statements and add ENGINE=InnoDB).

-- 
Ticket URL: <http://code.djangoproject.com/ticket/12421#comment:3>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-updates?hl=en.

Reply via email to