v ∞ Registration < ∞ --- 1 > Event (Registration.event) ^ ∞

问题描述 投票:0回答:1

我有5个模型,这些模型是用外键链接的,像这样。

Section (Registration.section)
^ 1
|
v ∞
Registration < ∞ --- 1 > Event (Registration.event)
^ ∞
|
v 1
User (Registration.user, Profile.user)
^ 1
|
v 1
Profile

从这些链接的模型中,我试图将数据显示在这样的表格中。

| ID             | Other Profile fields    | Section1                     | Section2                    | SectionN |
|----------------|-------------------------|------------------------------|-----------------------------|----------|
| user1.username | eg. user1.profile.grade | Registration.objects.get(    | Registration.objects.get(   |
                                           |    section=Section1,         |   section=Section1,         |
                                           |    user=user1   |   user=user1   |
                                           | ).event                      | ).event                     |
|----------------|-------------------------|------------------------------|-----------------------------|----------|
| user2.username | user2.profile.grade     | ...event                     |None (needs to handle this)  | 
|----------------|-------------------------|------------------------------|-----------------------------|----------|
| user3.username | user3.profile.grade     | None (needs to handle this)  |None (needs to handle this)  |          |

每个用户都有一条不同的记录 我不知道如何有效地获取每个科的注册信息。

我可以通过在python中使用字典和循环等方法手动操作数据,但这样做的效率太低,如果用户列表太大,我的服务器在完成这个过程之前就会超时。

我需要创建什么样的queryset结构才能在模板中输出这样的数据?

每个用户的每个部分只有一个注册对象。

class Registration(models.Model):

    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    section = models.ForeignKey(section, on_delete=models.CASCADE)

    class Meta:
        unique_together = ("event", "user", "section")
python django django-queryset
1个回答
0
投票

)

  1. 和values_list不会产生Model对象,所以会更快。
  2. Registration.objects.filter(user__in=[1,42,...]).values_list()
  3. 如果你需要所有的数据在一起,不过最稳健的解决方案是直接做缓存。用cron运行一个日常脚本,在后台做你的表,并把它存储在一个表中(通过一个
  4. ),如果这是一个选项。(即使你需要更多的最新数据,我也建议像这样的重度查询采用后台处理,在db中加入状态标志(key: input, status: processing or ready, data: PickleField)。

如果用户量很大,即使是在

-ed DB查询会很慢,使用关系型数据库.你的方法应该是最快的一种,因为它只是4-5个DB查询+处理。

join Registration.objects.values_list('event__property', 'user__username', 'user__profile__grade')

© www.soinside.com 2019 - 2024. All rights reserved.