2011-08-20 30 views
3

对于外键的多列唯一约束,MySQL似乎有些破裂。这是我能拿出来显示这个(使用MySQL/InnoDB的)最小的例子:我如何在MySQL中有一个涉及ForeignKey字段的unique_together约束?

models.py

from django.db import models 

class Team(models.Model): 
    pass 

class Player(models.Model): 
    team = models.ForeignKey(Team) 
    number = models.PositiveIntegerField() 

    class Meta: 
     unique_together = ("team", "number") 

运行schemamigration --initial,南吐出来,下面的迁移(唯一重要的位):

class Migration(SchemaMigration):                                     
    def forwards(self, orm): 
     # Adding model 'Team' 
     db.create_table('fkuniq_team', (
      ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), 
     )) 
     db.send_create_signal('fkuniq', ['Team']) 

     # Adding model 'Player' 
     db.create_table('fkuniq_player', (
      ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), 
      ('team', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['fkuniq.Team'])), 
      ('number', self.gf('django.db.models.fields.PositiveIntegerField')()), 
     )) 
     db.send_create_signal('fkuniq', ['Player']) 

     # Adding unique constraint on 'Player', fields ['team', 'number'] 
     db.create_unique('fkuniq_player', ['team_id', 'number']) 

而且在MySQL:

mysql> SHOW COLUMNS FROM fkuniq_player; 
+---------+------------------+------+-----+---------+----------------+ 
| Field | Type    | Null | Key | Default | Extra   | 
+---------+------------------+------+-----+---------+----------------+ 
| id  | int(11)   | NO | PRI | NULL | auto_increment | 
| team_id | int(11)   | NO | MUL | NULL |    | 
| number | int(10) unsigned | NO |  | NULL |    | 
+---------+------------------+------+-----+---------+----------------+ 

我想静静地南未能创造出我想要的独特约束。在Key专栏中,我看到id主键索引和team_id外键索引,但也应该有一个MULnumber行,因为应该就可以了UNIQUE指数与team_id。此外,从模型中移除unique_together约束会导致下迁移失败,出现错误:

Traceback (most recent call last): 
    ... 
    File "/home/aogier/uniques/../uniques/fkuniq/migrations/0002_auto__del_unique_player_number_team.py", line 12, in forwards 
    db.delete_unique('fkuniq_player', ['number', 'team_id']) 
    File "/home/aogier/.virtualenvs/uniques/lib/python2.7/site-packages/south/db/generic.py", line 479, in delete_unique 
    raise ValueError("Cannot find a UNIQUE constraint on table %s, columns %r" % (table_name, columns)) 
ValueError: Cannot find a UNIQUE constraint on table fkuniq_player, columns ['number', 'team_id'] 

我相信这是因为缺少MySQL没有发挥好,当外键约束和多列UNIQUE约束一致。对于ALTER TABLEhttp://dev.mysql.com/doc/refman/5.1/en/alter-table.html的MySQL文档有一个评论意见(参见下文,Hadi Rastgou评论)。

不管怎样,对于长期问题抱歉:没有人有办法让这项工作?即使我必须在原始SQL中的特定于MySQL的查询中编写代码,我也会喜欢在迁移中执行此操作的干净方式。或者,也许这在MySQL中是不可能做到的,在我花更多时间研究这个之前,这很好理解。

回答

相关问题