Django,将User与另一个表联系起来

时间:2014-03-21 16:23:42

标签: database django model relationship

所以我得到了下图所示的表格:

database

我想要做的是创建一个关系,以便每个用户(django auth_user )将注册(或能够注册)到一个" 课程"这样他就可以看到他的模块的下一个活动。

我是否必须创建另一个表并放置2个外键,或者这是在' php'中执行此操作的方法。 Django会更简单吗?我被建议创建学生'模型继承自用户'在auth上使用扩展行为和一对多关系。我试图这样做,但遗憾的是没有结果,因为我对Django& amp;蟒。

2 个答案:

答案 0 :(得分:2)

如果每个auth_user(或auth.User)都有机会在课程中注册,我会创建一个与django User模型具有1对1关系的“用户配置文件”模型。您可以在此模型中存储其他用户数据,包括他们注册的课程。有关详细信息,请参阅https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model,但这是一个示例:

class UserProfile(models.Model):
    user = models.OneToOneField('auth.User')
    course = models.ForeignKey('courseapp.Course', null=True)

您可能需要创建一个每次保存auth.User对象时触发的信号,这样如果它是第一次保存User对象,它会自动创建UserProfile:

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from yourusersapp.models import UserProfile

def create_user_profile(sender, instance, created, **kwargs):
    # Automatically creates a UserProfile on User creation.
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

当您查询User对象时,您可以引用User对象的配置文件,如:

user_object.userprofile

然后,您可以创建一个Course对象,并通过UserProfile将user_object间接链接到该课程:

course = Course.objects.create(name='course_name', next_field='whatever')
user_profile = user_object.userprofile
userprofile.course = course
userprofile.save()

现在您拥有一个UserProfile的用户对象,该用户对象仅链接到1门课程。许多用户可以使用相同的课程,但用户只能使用1门课程。您还可以引用特定课程的所有用户,例如:

course = Course.objects.get(name='course_name')
course_users = course.userprofile_set.all()

HTH

答案 1 :(得分:1)

我认为你可以采用以下两种方式之一。

  1. 扩展用户模型。 '学生'对你的新车型来说可能是一个好名字。它与用户'有一个OneToOne关系,与' Course'有一个ForeignKey关系。它可以存储仅适用于学生的任何其他信息。有关如何执行此操作的文档,请访问https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#extending-the-existing-user-model

  2. 创建与课程具有ForeignKey关系的自定义用户模型。这种方法有点复杂,但产生的结果略微清晰。有关的文档在这里。 https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#substituting-a-custom-user-model

  3. 很抱歉,如果我似乎只是将您发送到Django文档,但这两个部分都写得很好,应该很清楚地解释一下。如果您想发布带有示例代码的其他问题,我们可以尝试了解您扩展用户模型的原始尝试无法正常工作的原因。顺便说一句,你的学生"模型不应该继承用户模型以扩展它。