4

我有多个 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那么我该怎么做呢?

4

1 回答 1

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
于 2012-09-22T10:21:38.237 回答