2011-07-08 52 views
1

我有兩個型號,組合鍵:複合鍵

class ContestUser(models.Model): 
    user_id = models.IntegerField(primary_key = True) 
    contest_id = models.IntegerField(primary_key = True) 
    username = models.CharField(max_length = 1536, blank = True) 
    . 
    . 
    . 



class ContestRegistration(models.Model): 
    user_id = models.IntegerField(primary_key = True) 
    contest_id = models.IntegerField(primary_key = True) 
    status = models.IntegerField(choices = EJUDGE_CONTEST_STATUSES) 
    . 
    . 
    . 

首先的問題是如何能與他們和查詢一樣加入進來。

從ContestRegistration中選擇*加入ContestUser在r.user_id = u.user_id和r.contest_id = u.contest_id其中r.contest_id = 3;

二是如何保存這樣的對象?

cuser = ContestUser.objects.get(user_id = 1, contest_id = 1) 
cuser.username = 'username' 
cuser.save() 

這導致IntegrityError:(1062, 「關鍵 '主要' 重複條目 '1-1'」)

執行的SQL是:

SELECT * FROM `users` WHERE (`users`.`contest_id` = 1 AND `users`.`user_id` = 1); 
SELECT (1) AS `a` FROM `users` WHERE `users`.`user_id` = 1 LIMIT 1; 
UPDATE `users` SET ... WHERE `users`.`user_id` = 1 ; 

回答