django:具有反向外键的型号?

时间:2010-10-06 21:15:39

标签: django foreign-keys models

我这里有鸡和蛋的问题。首先,我有一个userprofile类,它基于django的默认用户模型。

class UserProfile(models.Model):
    def __unicode__(self):
        return self.user.username
    user = models.OneToOneField(User, unique=True)
    exam = models.ForeignKey('questions.Exam', null=True)

接下来,我有一个考试课

class Exam(models.Model):
    def __unicode__(self):
        return self.id
    user = models.ForeignKey(UserProfile)

UserProfile和Exam模型位于不同的应用程序中。但是,他们彼此都有外国钥匙。我知道它的设计不好,但在我的情况下这是我特有的要求。但是,检查的UserProfile外键可以为Null。但每当我尝试在管理员中创建考试时,我都会收到错误消息“UserProfile”是必填字段。当我尝试创建用户时,会发生相反的情况。有没有办法打破这种僵局?或者我应该重新设计我的应用程序?

1 个答案:

答案 0 :(得分:1)

  

我应该重新设计我的应用吗?

几乎可以肯定。但是,这个实际问题是由于您拥有null=True,它正确设置数据库以允许外键字段上的null,但您尚未添加blank=True,这是Django用来验证正确条目的内容。添加它,这个部分至少应该有效。