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
上的外键索引,但MUL
行中也应该有number
因为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']
我相信它缺失了,因为当外键约束和多列UNIQUE
约束重合时,MySQL不能很好地发挥作用。对于ALTER TABLE
:http://dev.mysql.com/doc/refman/5.1/en/alter-table.html的MySQL文档有一个评论:(见左下角,Hadi Rastgou的评论)。
无论如何,抱歉这个长期的问题:有没有人有办法让这项工作?即使我必须在原始SQL中编写特定于MySQL的查询,我也希望在迁移过程中能够以一种干净的方式执行此操作。或许这可能只是在MySQL中无法做到,在我花更多时间研究这个之前,这将是一件好事。