[Django] 同じモデルに対して複数の外部キーを設定したい

Django で同じモデルに対して複数の外部キーを設定したかったのですが、ちょとハマったのでメモ

例えば、試合モデルとチームモデルがあって、試合モデルにホームチームとアウェイチームを関連付けたい

DB的に言うとこんな感じ

CREATE TABLE `team` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(80) NOT NULL
);
CREATE TABLE `game` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`game_date` datetime NOT NULL,
`home_team_id` integer NOT NULL,
`away_team_id` integer NOT NULL
);

んでモデルの定義はこんな感じにしてみた

class Team(models.Model):
name = models.CharField(max_length=80)

class Game(models.Model):
game_date = models.DateTimeField()
home_team = models.ForeignKey(Team)
away_team = models.ForeignKey(Team)

んでsyncdbしてみたらこんなエラー出た

Error: One or more models did not validate:
hoge.game: Accessor for field ‘home_team’ clashes with related field ‘Team.game_set’. Add a related_name argument to the definition for ‘home_team’.
hoge.game: Accessor for field ‘away_team’ clashes with related field ‘Team.game_set’. Add a related_name argument to the definition for ‘away_team’.

しばらく悩み調べた結果related_nameを定義すればおkだった。

class Team(models.Model):
name = models.CharField(max_length=80)

class Game(models.Model):
game_date = models.DateTimeField()
home_team = models.ForeignKey(Team, related_name="home_team")
away_team = models.ForeignKey(Team, related_name="away_team")

参考ページ

Multiple Foreign Keys to same Table?

Filed under: Django,Programming,Python — maesan 1:11 AM

[Django] CSRF verification failed.

取りあえずDjangoはじめて、とりあえずformつくって、とりあえずPOSTしてみて「CSRF verification failed.」って出たらsettings.pyのMIDDLEWARE_CLASSESにdjango.middleware.csrf.CsrfResponseMiddlewareを入れとくとおk


MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware', # <-コレ
)
Filed under: Django,Programming,Python — maesan 7:30 PM
 iTunes Store(Japan)
 iTunes Store(Japan)
 iTunes Store(Japan)
 iTunes Store(Japan)
 iTunes Store(Japan)