Django模型:使用多个值作为键?
Posted
技术标签:
【中文标题】Django模型:使用多个值作为键?【英文标题】:Django models: Use multiple values as a key? 【发布时间】:2011-02-15 02:44:33 【问题描述】:这是一个简单的模型:
class TakingCourse(models.Model):
course = models.ForeignKey(Course)
term = models.ForeignKey(Term)
我不想使用 Django 创建默认主键,而是使用 course
和 term
作为主键 - 合在一起,它们唯一地标识一个元组。这是 Django 允许的吗?
在相关说明中:我试图代表用户以某些术语参加课程。有没有更好的方法来做到这一点?
class Course(models.Model):
name = models.CharField(max_length=200)
requiredFor = models.ManyToManyField(RequirementSubSet, blank=True)
offeringSchool = models.ForeignKey(School)
def __unicode__(self):
return "%s at %s" % (self.name, self.offeringSchool)
class MyUser(models.Model):
user = models.ForeignKey(User, unique=True)
takingReqSets = models.ManyToManyField(RequirementSet, blank=True)
takingTerms = models.ManyToManyField(Term, blank=True)
takingCourses = models.ManyToManyField(TakingCourse, blank=True)
school = models.ForeignKey(School)
class TakingCourse(models.Model):
course = models.ForeignKey(Course)
term = models.ForeignKey(Term)
class Term(models.Model):
school = models.ForeignKey(School)
isPrimaryTerm = models.BooleanField()
【问题讨论】:
【参考方案1】:您可以使用unique_together 选项。
class TakingCourse(models.Model):
course = models.ForeignKey(Course)
term = models.ForeignKey(Term)
class Meta:
unique_together = ('course', 'term')
不过,如果你这样做会更好:
class MyUser(models.Model):
user = models.OneToOneField(User)
takingReqSets = models.ManyToManyField(RequirementSet, blank=True)
takingCourses = models.ManyToManyField(Course, through='TakingCourse', blank=True, null=True)
school = models.ForeignKey(School)
class TakingCourse(models.Model):
my_user = models.ForeignKey(MyUser)
course = models.ForeignKey(Course)
term = models.ForeignKey(Term)
class Meta:
unique_together = ('my_user', 'course')
了解one to one relationships 和extra fields on many to many relationships。
【讨论】:
以上是关于Django模型:使用多个值作为键?的主要内容,如果未能解决你的问题,请参考以下文章
Django Forms - 构建一个表单,显示来自多个不同模型的字段,但按外键排序