我想列出所有评论过各种博客文章的教师学生。以下是我的最大努力,但我重复了每个类型的学生姓名,因此如果他们评论多个可怕的博客帖子,他们的名字会多次列出。如何在教师资料页面上的每个类型旁边列出每个学生姓名?
Models.py
class Genre(models.Model):
name = models.CharField(max_length=200, unique=True)
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile')
username = models.CharField(max_length=128, unique=True)
teacher = models.ForeignKey('Teacher', blank=True, null=True)
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='teacher_profile')
name = models.CharField(max_length=128, blank=True, unique=True)
class BlogPost(models.Model):
genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=True)
class Comment(models.Model):
blogpost = models.ForeignKey(BlogPost, related_name='comments', on_delete = models.CASCADE, null=True)
message = CharField(max_length=1000, blank=True)
commenter = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE, null=True)
Views.py
def teacher_profile(request):
student_list = Student.objects.filter(teacher__user=request.user)
student_blogpost_list = BlogPost.objects.filter(comments__commenter__student_profile__teacher__user=request.user).distinct()
student_genre_list = Genre.objects.filter(blogpost__in=student_blogpost_list).distinct()
return render(
request,
'myapp/teacher_profile.html',
context= {'student_list':student_list, 'student_blogpost_list':student_blogpost_list, 'student_genre_list':student_genre_list},
)
teacher_profile.html
{% if student_genre_list %}
<h4>Genres</h4>
{% for genre in student_genre_list %}
Genre: {{ genre.name }} - Students:
{% for blogpost in genre.blogpost_set.all %}
{% for comment in blogpost.comments.all %}
{% if comment.commenter.student_profile in student_list %}
{{ comment.commenter.student_profile.username }}
{% endif %}
{% endfor %}
{% endfor %}
<br>
{% endfor %}
{% endif %}
答案 0 :(得分:0)
我想可以通过以下方式完成:
student_list = Student.objects.filter(teacher__user=request.user)
student_blogpost_list = BlogPost.objects.filter(comments__commenter__student_profile__teacher__user=request.user).distinct()
data = dict()
for blogpost in student_blogpost_list:
students_usernames = list(blogpost.comment_set.filter(commenter__in=student_list).
values_list('commenter__student_profile__username', flat=True))
if blogpost.genre.name in data:
data[blogpost.genre.name].append(students_usernames)
else:
data[blogpost.genre.name] = students_usernames
for key in data.keys():
data[key] = set(data[key]) # remove duplicates from list
data
变量将等于:
{'genre_1': {'username_1', 'username_2'}, 'genre_2': {'username_2', 'username_3', 'username_4'}}
我的观点是模板中不应该有很多逻辑。使用这种方法,您只需要迭代结果字典。 尽管如此,我无法保证此代码正常工作,因为我没有使用相同的方案设置数据库。