Django ORM 多个 table 加入 AbstractUser

Django ORM multiple table join with AbstractUser

我用谷歌搜索但在多个 table 连接(与 1:1、1:n 和 n:m 关系)中感到困惑。我的模型看起来像这样:

class User(AbstractUser):
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)

class Event(models.Model):
    owner_events = models.ForeignKey(User, on_delete=models.CASCADE, related_name='events')
    name = models.CharField(max_length=30)
   date = models.DateTimeField(default=timezone.now)

    def get_absolute_url(self): # defekt
        return reverse('event_detail', kwargs={'pk': self.pk})
        return self.name

    def get_event(self):
        name = escape(self.name)
        date =  escape(self.date)
        return "Name: " + str(name) + " Datum: " + str(date)

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    interests = models.ManyToManyField(Subject, related_name='interested_teachers') 
    matches = models.ManyToManyField(Match, related_name="teacher_matches")

    def __str__(self):
        return self.user.username

    def get_events(self):
        return "Name: " + str(self.events.name) + "Date: "

    def get_events_adr(self):
        return self.events

    def get_interests(self):
        return "Interests: " + str(self.interests.name)

这是 table 在数据库中的样子:

Classroom_Event

Classroom_Teacher

Classroom_User

我想在视图中显示事件(event_id、姓名、日期)和教师信息(user_id、姓名)。在 SQL 中会是这样的:

select classroom_event.id, classroom_event.name, classroom_event.date,
classroom_user.id, classroom_user.username from classroom_event

left join classroom_user on
classroom_event.owner_events_id = classroom_user.id

left join classroom_teacher on 
classroom_user.id = classroom_teacher.user_id

我认为没有必要创建抽象用户。 只需为学生和教师定义两个模型,并为默认用户模型提供主题 one_to_one 键,也不需要 student/teacher 字段!。 只是为了更好地从 User 模型反向调用这两个模型,在外键字段中给出 related_name,否则将有默认的 "teacher_set" reverse.

for teacher in Teacher.objects.all():
    print(teacher.user.username)

或反过来:

for user in User.objects.all():
   if user.teacher:
        print(user.teacher.username)