python - 从查询 Django 访问模型方法 "def()"

标签 python django

我正在和这里的一些东西打架,我正在使用 Django,希望你能帮助我。

我有一个带有 date_of_birth 字段的 Account 模型,我有一个方法可以找出年龄。

class Account(AbstractBaseUser, PermissionsMixin):
     date_of_birth   = models.DateField()
     def age(self):
        """
        Returns the age from the date of birth
        """
        today = datetime.date.today()
        try: 
            birthday = self.date_of_birth.replace(year=today.year)
        except ValueError: # raised when birth date is February 29 and the current year is not a leap year
            birthday = self.date_of_birth.replace(year=today.year, day=self.date_of_birth.day-1)
        if birthday > today:
            return today.year - self.date_of_birth.year - 1
        else:
            return today.year - self.date_of_birth.year

我想知道是否可以从这样的查询中获取年龄:

list = Account.objects.filter('account__age__gte', today)

我已经试过了,但我得到了这个错误:

cannot resolve keyword 'age' into field. Choices are:......

并且只显示字段。不是方法。\

感谢您的帮助。

非常感谢。

最佳答案

您不能直接查询模型方法,因为自定义方法无法评估其相应的 SQL 查询。

您有几个选择:

在 View 中,计算给定年龄的最早出生日期。示例 24 年:

from dateutil.relativedelta import relativedelta

datetime.date.today() - relativedelta(years=24)
datetime.date(1989, 11, 15)

现在,查询将针对 date_of_birth 字段。

请注意,dateutil 是第 3 方库,默认情况下可能不适用于您的 python。 (如果你想使用 timedelta,你也可以这样做,因为 datetime.timedelta 是 python 内置的)

另一种选择(效率稍低)是获取对象查询集,并使用列表理解来过滤掉不需要的记录。

qs = Account.objects.all()

qs = [account for account in qs if account.age() > 24]

24,显然只是一个例子。用一些“理智”值代替它。

关于python - 从查询 Django 访问模型方法 "def()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20004427/

相关文章:

Django URL - 渲染时捕获 NoReverseMatch

python - : in node causing Keyerror in xmlparsing using ElementTree

python - 如何编写Django模型以从多个表中获取记录?

python - 有没有办法让 == 在 vi​​m 中工作以重新缩进 python 代码?

python - 如何避免 python 2.7 中的“无效模式或文件名”错误?

python - Vagrant Flask 应用程序重新加载速度非常慢

python - 在 Python matplotlib 中保留尺寸的同时提高图形的分辨率

python - 具有多个强制参数的 RESTful URI 的最佳设计是什么?

python - 日期时间对象不适用于 weekday()

python - 用户创建成功后django用户登录失败