views:

52

answers:

1

Here is a simple model:

class TakingCourse(models.Model):
    course = models.ForeignKey(Course)
    term = models.ForeignKey(Term)

Instead of Django creating a default primary key, I would like to use both course and term as the primary key - taken together, they uniquely identify a tuple. Is this allowed by Django?

On a related note: I am trying to represent users taking courses in certain terms. Is there a better way to do this?

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  A: 

You can use the unique_together option.

class TakingCourse(models.Model):
    course = models.ForeignKey(Course)
    term = models.ForeignKey(Term)

    class Meta:
        unique_together = ('course', 'term')

It would be better if you do something like this, though:

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')

Read about one to one relationships and extra fields on many to many relationships.

jbochi