具有Model方法的Django queryset包含另一个queryset [英] Django queryset with Model method containing another queryset
问题描述
假设我有一个模型 MyModel
,该模型具有使用另一模型的查询集的属性方法.
class OtherModel(models.Model)...类MyModel(models.Model):simple_attr = models.CharField('Yada yada')@财产def complex_attr():list_other_model = OtherModel.objects.all()...#使用来自'OtherModel'和simple_attr的queryset的复杂算法返回结果
这将导致我在 MyModel
上的 get_queryset()
方法查询数据库以每次为每一行生成 list_other_model
变量./p>
这导致我的MyModel ListView
生成数百个SQL查询.效率不高.
当使用 MyModel.objects.all()
时,如何构造Manager或get_queryset方法为每行缓存变量 list_other_model
?
我希望我的问题是有道理的-我正在尝试第六杯意式浓缩咖啡,但仍然没有找到减少db查询的方法.
不确定这是否是最好的方法,但是可以.
如果有人发布更好的答案,我会接受他们的答案.
class OtherModel(models.Model)...类MyModelManager(models.Manager):def get_queryset(self):self.model.list_other_model = OtherModel.objects.all()返回super(MyModelManager,self).get_queryset()类MyModel(models.Model):simple_attr = models.CharField('Yada yada')list_other_model =无对象= MyModelManager()@财产def complex_attr():...#使用来自'OtherModel'和simple_attr的queryset的复杂算法返回结果
Suppose I have a model, MyModel
, with a property method that uses another model's queryset.
class OtherModel(models.Model)
...
class MyModel(models.Model):
simple_attr = models.CharField('Yada yada')
@property
def complex_attr(self):
list_other_model = OtherModel.objects.all()
...
# Complex algorithm using queryset from 'OtherModel' and simple_attr
return result
This causes my get_queryset()
method on MyModel
to query the database to generate the list_other_model
variable every time for every single row.
Which causes my MyModel ListView
to generate hundreds of SQL queries. Not efficient.
How can I architect a Manager or get_queryset method to cache the variable list_other_model
for each row when using MyModel.objects.all()
?
I hope my question makes sense--I'm on my sixth shot of espresso, and still haven't found a way to reduce the db queries.
Not sure if this is the best way to do it, but it works.
If someone posts a better answer, I'll accept theirs.
class OtherModel(models.Model)
...
class MyModelManager(models.Manager):
def get_queryset(self):
self.model.list_other_model = OtherModel.objects.all()
return super(MyModelManager, self).get_queryset()
class MyModel(models.Model):
simple_attr = models.CharField('Yada yada')
list_other_model = None
objects = MyModelManager()
@property
def complex_attr(self):
...
# Complex algorithm using queryset from 'OtherModel' and simple_attr
return result
这篇关于具有Model方法的Django queryset包含另一个queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!