Django queryset with Model method containing another queryset

这一生的挚爱 提交于 2021-02-08 07:17:16

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/28598178/django-queryset-with-model-method-containing-another-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!