我有Product
作为模特。
我正在重构一些代码,并且有一个重复的查询遍布代码库,需要替换。
所以我想集中这个查询,以便封装它的逻辑。
我想要像
这样的东西 <an_object>.get_uncompleted_products(products);
在这种情况下,保留现有代码,products
已经是查询的结果(products = Products.objects.filter(filter_expression)
)
这只是一个方便的问题,我知道可能的答案,但你会把get_uncompleted_products()
放在哪里,什么可能是一个好的“django-way”解决方案?
我最初想把它放在Product
模型上。但我认为Product
方法直接在单个模型引用上工作,因此签名需要是:
class Product(models.Model):
@classmethod
get_uncompleted_products(list)
我不确定为什么这让我感觉不那么合适。一种可能的替代方案是将其放入实用程序模块中。我也可以在视图模块中使用它,但它似乎在其他视图中也大量使用,所以我更喜欢某些更通用的地方。
答案 0 :(得分:1)
我猜'django方式'是将它定义为自定义管理器方法,而不是类方法,在类方法的情况下,可以在具有组合而不是继承的不同模型之间共享。
from django.db import models
class ProductQuerySet(models.query.QuerySet):
def get_uncompleted_products(self):
...
class ProductManager(models.Manager):
def get_queryset(self):
return ProductQueryset(self.model, using=self._db)
def get_uncompleted_products(self):
# defined twice to resolve queryset chaining issue with custom managers
return self.get_queryset().get_uncompleted_products()
class Product(models.Model):
...
objects = ProductManager()