<p>当然可以,你可以试试这个</p>
<pre><code>from django.db import models
class Chapter(models.Model):
name = models.TextField()
def get_lessons(self):
"""return all lessions filtered by specific chapter"""
return Lesson.objects.filter(chapter__pk=self.pk)
class Lesson(models.Model):
chapter = models.ForeignKey(Chapter)
owner = models.ForeignKey(User)
name = models.TextField()
def get_user_chapters(self):
"""return all chapters by specific `chapter` and `user` in this lession"""
return UserChapterScore.objects.filter(chapter=self.chapter, user=self.owner)
def get_user_scores(self):
"""return total scores by specific `chapter` and `user` in this lession"""
return self.get_user_chapters().aggregate(models.Sum('score'))['score__sum']
class UserChapterScore(models.Model):
chapter = models.ForeignKey(Chapter)
user = models.ForeignKey(User)
score = models.IntegerField(default=0)
</code></pre>
<p>更新,你可以每一个它</p>
<pre><code>lessons = [{
'lessons': chapter.get_lessons(), # return queryset of lessons
'lessons_detail': [
{
'owner': c.owner,
'scores': c.get_user_scores(),
'chapters': c.get_user_chapters()
} for c in chapter.get_lessons()
]
} for chapter in Chapter.objects.all()]
</code></pre>