Django项目中与实例无关的模型相关逻辑放在哪里

2024-04-23 10:03:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码片段来选择表中的最后一个日期,然后执行一些逻辑来获取新的日期。django项目应该把这种逻辑放在哪里?我见过一些Fat模型的例子,其中逻辑被作为模型的一种方法,但据我所知,这只适用于一个实例。你知道吗

# models.py
class PurchasesDetails(models.Model):
    purchaseid = models.AutoField(primary_key=True)
    effectivedate = models.DateField()

    def getselecteddate(self):
        lastdate = PurchasesDetails.objects.filter().aggregate(Max('effectivedate'))
        lastdate = next (iter (lastdate.values()))
        thisweekday = lastdate.weekday()
        advancedays = 1
        if thisweekday ==4:
            advancedays = 3
        thisdate = (lastdate + timedelta(days=advancedays))

        return thisdate

Tags: 项目django方法代码模型models逻辑fat
1条回答
网友
1楼 · 发布于 2024-04-23 10:03:22

official docs中所述,model manager看起来是定义此类逻辑的最佳位置

Define custom methods on a model to add custom “row-level” functionality to your objects. Whereas Manager methods are intended to do “table-wide” things, model methods should act on a particular model instance.

This is a valuable technique for keeping business logic in one place – the model.

例如,在你的情况下

class _DetailsManager(models.Manager):

    def getselecteddate(self):
        lastdate = PurchasesDetails.objects.filter().aggregate(Max('effectivedate'))
        lastdate = next (iter (lastdate.values()))
        thisweekday = lastdate.weekday()
        advancedays = 1
        if thisweekday == 4:
            advancedays = 3
        thisdate = (lastdate + timedelta(days=advancedays))

        return thisdate

class PurchasesDetails(models.Model):
    purchaseid = models.AutoField(primary_key=True)
    effectivedate = models.DateField()
    objects = _DetailsManager()

new_date = PurchasesDetails.objects.getselecteddate()

请阅读here专门用于定制模型管理器的特定文档。你知道吗

相关问题 更多 >