我试图找出一种方法可以避免将这么多参数传递给我的应用程序中的函数。我为每个表使用不同的数据库,因此无法加入,因此我需要创建一个主键字典,其中包含后续函数所需的对象。我这样做是为了只做两个查询。
我的例子如下。请注意我必须如何将people_ref
参考字典传递给每个变形函数。我想做的是设置某种people_ref
可以从任何地方访问的全局变量。这样我就可以将 People.in_bulk() 响应转储到全局池,然后直接从变形函数内部访问它,而无需传入引用。有没有办法做到这一点?
我想叫什么:
>>> myapp.models.make_crazy_books([1,2,3])
来自 myapp/models.py:
import itertools
from django.db import models
from myapp.utils import deform
class People(models.Model):
born = model.DateField()
class Book(models.Model):
author = models.ForeignKey(People, related_name='author_set')
editor = models.ForeignKey(People, related_name='editor_set')
last_edition = model.DateField()
def make_crazy_books(book_ids):
book_list = Book.objects.using("db1").filter(id__in=book_ids) #Query here, db1
people_list = ((b.author_id, b.editor_id) for b in book_list)
people_ids = set(itertools.chain(*people_list))
people_ref = People.objects.using("db2").in_bulk(people_ids) #Query here, db2
#Would like to not have to send people_ref to each function
book_list = deform.deform_edition(book_list, people_ref)
book_list = deform.deform_author(book_list, people_ref)
""" ... do some other deforming functions """
return book_list
来自 mayapp/utils/deform.py:
def deform_edition(book_list, people_ref):
for book in book_list:
author = people_ref[book.author_id] #Change to global lookup?
b.last_edition = author.born
return book_list
def deform_author(book_list, people_ref):
for book in book_list:
editor = people_ref[book.editor_id] #Change to global lookup?
b.author = editor
return book_list
我会尝试使用 Django 的缓存功能,但是在运行多个线程的情况下,缓存的引用字典可以被其他同时请求读取/覆盖。
编辑:也许本地内存缓存会起作用,因为它是线程安全的?