說我有2種型號:Django的ORM:選擇與設置
class Poll(models.Model):
category = models.CharField(u"Category", max_length = 64)
[...]
class Choice(models.Model):
poll = models.ForeignKey(Poll)
[...]
給定一個民意調查對象,我可以查詢它的選擇與:
poll.choice_set.all()
但是,有沒有效用函數查詢一系列民意調查中的所有選擇?
事實上,我正在尋找類似下面的(這是不支持的,我不求怎麼可能):
polls = Poll.objects.filter(category = 'foo').select_related('choice_set')
for poll in polls:
print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration
我做了(醜陋的)函數來幫我實現這一目標:
def qbind(objects, target_name, model, field_name):
objects = list(objects)
objects_dict = dict([(object.id, object) for object in objects])
for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}):
id = getattr(foreign, field_name + '_id')
if id in objects_dict:
object = objects_dict[id]
if hasattr(object, target_name):
getattr(object, target_name).append(foreign)
else:
setattr(object, target_name, [foreign])
return objects
被用作如下:
polls = Poll.objects.filter(category = 'foo')
polls = qbind(polls, 'choices', Choice, 'poll')
# Now, each object in polls have a 'choices' member with the list of choices.
# This was achieved with 2 SQL queries only.
有什麼更容易已經p由Django推出?或者至少,一個片段以更好的方式做同樣的事情。
你通常如何處理這個問題?
也許你的qbind函數是可以完成的最好的。但是將它打包到自定義管理器中可能有意義 - http://docs.djangoproject.com/en/dev/topics/db/managers/#id2 – NathanD 2009-05-12 16:11:41