【问题标题】:I have multiple django tables and want to query the tables in parallel我有多个 django 表并希望并行查询这些表
【发布时间】:2012-09-22 06:58:38
【问题描述】:

我有多个 db 表映射到不同的 django 模型。现在我希望使用线程并行查询它们。例如:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True);

    isATutor = models.BooleanField();
    timeAvailable = models.CharField(max_length=3);

class TutorProfile(models.Model):
    user = models.ForeignKey(User);

    language = models.CharField(max_length=30);
    unique_together = (("user", "language"), );

class Tutor(models.Model):
    user = models.ForeignKey(User);

    subject = models.CharField(max_length=30);
    unique_together = (("user", "subject"), );

现在,假设我想使用线程查询 UserProfile 表中的 timeAvailable 字段和 TutorProfile 表中的 language 字段和 Tutor 表中的 subject 字段。那我该怎么做呢?

【问题讨论】:

  • 你为什么要这样做?是什么让您认为线程就是答案?
  • 为什么需要并行查询?
  • @user1690465 您要单独询问数据吗?例如:一个线程获取 UserProfiles,第二个 TutorProfiles 和 3rd Tutors ?
  • 您要解决的问题是什么?
  • 我有几个表,想根据从数据库中获取的各种数据执行复杂的计算。此外,我想让我的系统尽可能实时。所以,比如说,我想添加两个存储在 2 个不同 dbtable 中的数字,并且我想添加它们。所以我想同时获取它们,然后对获取的数字进行操作。这是我想要构建的应用程序的一个非常幼稚的示例。

标签: django multithreading django-models


【解决方案1】:

这只是一个小插曲,但也许会有所帮助:

import threading
class PararellThread(threading.Thread):
     def __init__(self,model):
         threading.Thread.__init__(self)
         self.model = model
         self.result = []

     def run(self):
         self.result = self.model.objects.all()

def get_objects_in_pararell( models ):
    threads = []
    result = []
    for model in models:
        t = PararellThread(model)
        t.start()
        threads.append(t)

    for thread in threads:
        thread.join()
        for obj in thread.result:
             result.append(obj)

    return result

【讨论】:

  • 我有几个表,想根据从数据库中获取的各种数据执行复杂的计算。此外,我想让我的系统尽可能实时。所以,比如说,我想添加两个存储在 2 个不同 dbtable 中的数字,并且我想添加它们。所以我想同时获取它们,然后对获取的数字进行操作。这是我想要构建的应用程序的一个非常幼稚的示例。
  • 您听说过数据库视图吗?看看stackoverflow.com/questions/1041855/use-database-view-in-django如何在django中管理它们
猜你喜欢
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
相关资源
最近更新 更多