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