如果每个 auth_user(或 auth.User)都将或有机会注册课程,我将创建一个与 django User 模型具有一对一关系的“用户配置文件”模型。您可以在此模型中存储其他用户数据,包括他们注册的课程。请参阅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_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 门课程。许多用户可以上同一门课程,但一个用户只能上一门课程。您还可以参考特定课程的所有用户,例如:
course = Course.objects.get(name='course_name')
course_users = course.userprofile_set.all()
HTH