我有一个配置文件查询集:
模型:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True)
...
看法:
Profile.objects.select_related('user')
每个用户/个人资料每天可以注册多个活动:
楷模:
class Event(models.Model):
title = models.CharField(max_length=120)
date = models.DateField(default=default_event_date)
...
class Registration(models.Model):
event = models.ForeignKey(Event)
student = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
block = models.ForeignKey(Block, on_delete=models.CASCADE)
....
给定一个日期,我如何注释(?我认为这就是我想要的?)每个块一个注册对象(根据用户/配置文件和 Event__Date 过滤)
最后,我试图在我的模板中输出的是这样的:
For Date: 19 Dec 2016
User/Profile Block A Block B ...
user1 None None
user2 Event1 Event2
user3 Event3 None
...
编辑
尝试 1. 这是我第一次尝试完成此操作。我怀疑这是非常低效的,并且在生产中会非常缓慢,但至少它有效。如果有人可以提供更有效和优雅的解决方案,将不胜感激!(请注意,这还包括对 homeroom_teacher 的用户配置文件模型的过滤器,该过滤器未包含在原始问题中,但我已离开此处,因为这是有效的代码)
注册模型经理
类RegistrationManager(models.Manager):
def homeroom_registration_check(self, event_date, homeroom_teacher):
students = User.objects.all().filter(is_staff=False, profile__homeroom_teacher=homeroom_teacher)
students = students.values('id', 'username', 'first_name', 'last_name')
# convert to list of dicts so I can add 'annotate' dict elements
students = list(students)
# get queryset with events? optimization for less hits on db
registrations_qs = self.get_queryset().filter(event__date=event_date, student__profile__homeroom_teacher=homeroom_teacher)
# append each students' dict with registration data
for student in students:
user_regs_qs = registrations_qs.filter(student_id=student['id'])
for block in Block.objects.all():
# add a new key:value for each block
try:
reg = user_regs_qs.get(block=block)
student[block.constant_string()] = str(reg.event)
except ObjectDoesNotExist:
student[block.constant_string()] = None
return students
模板 请注意,block.constant_string() --> "ABLOCK"、"BBLOCK" 等,这是在 block.constant_string() 方法中硬编码的,我也不知道如何解决这个问题。
{% for student in students %}
<tr >
<td>{{ student.username }}</td>
<td>{{ student.first_name }}</td>
<td>{{ student.last_name }}</td>
<td>{{ student.ABLOCK|default_if_none:'-' }}</td>
<td>{{ student.BBLOCK|default_if_none:'-' }}</td>
</tr>
{% endfor %}