0

我用谷歌搜索,但对多表连接(具有 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)

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

课堂_活动

课堂_教师

教室_用户

在视图中,我希望显示事件(事件 ID、姓名、日期)和教师信息(用户 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
4

1 回答 1

0

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

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

或反过来:

for user in User.objects.all():
   if user.teacher:
        print(user.teacher.username)
于 2020-02-23T15:10:36.663 回答