互连外键

时间:2011-10-18 11:19:23

标签: python django

我有一个任务:

  • 使用基本上为“student”和“group”的数据库模型。
  • '学生'包含:'姓名','学生证','群组'(必须是ForeigKey to Group!
  • '群组'包含:'群组名称'和'队长'(必须是学生的外键!

现在我发生了碰撞 - 直接说不可能。所以我这样做了:

class Group(models.Model):
    group_name = models.CharField(max_length=50)    


class Student(models.Model):
    name = models.CharField(max_length=50)
    birth_date = models.DateField()
    std_ID_card = models.IntegerField()
    group = models.ForeignKey(Group)


class Captain(models.Model):
    student = models.OneToOneField(Student)
    group = models.OneToOneField(Group)

我有更优雅和正确的方法吗?

2 个答案:

答案 0 :(得分:2)

尝试添加related_name

class Student(models.Model):
    name = models.CharField(max_length=50)
    birth_date = models.DateField()
    std_ID_card = models.IntegerField()
    group = models.ForeignKey('Group')

class Group(models.Model):
    group_name = models.CharField(max_length=50)    
    captain = models.ForeignKey('Student', related_name='%(class)s_captain')

答案 1 :(得分:1)

为什么原始结构不可能?

class Group(models.Model):
    group_name = models.CharField(max_length=50)    
    captain = models.ForeignKey('Student')

class Student(models.Model):
    name = models.CharField(max_length=50)
    birth_date = models.DateField()
    std_ID_card = models.IntegerField()
    group = models.ForeignKey(Group)