我有两个带有复合键的模型:
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中选择* r在r.user_id = u.user_id和r.contest_id = u.contest_id上加入ContestUser,其中r.contest_id = 3;
其次是如何保存这样的对象?
cuser = ContestUser.objects.get(user_id = 1, contest_id = 1)
cuser.username = 'username'
cuser.save()
这导致IntegrityError:(1062,“重复条目'1-1'用于密钥'PRIMARY'”)
执行的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 ;
答案 0 :(得分:0)
Django模型不支持多个主键:https://docs.djangoproject.com/en/1.3/faq/models/#do-django-models-support-multiple-column-primary-keys
但是,正如文档所描述的那样,您可以在ForeignKey字段上使用其他属性,例如unique_together来执行相同的操作。希望能帮到你。