Django找不到模型属性

时间:2019-05-29 14:18:17

标签: python django

在我的Django项目中,我有一个models.py,看起来像这样:

from django.db import models

class Battle(models.Model):

    def __str__(self):
        return self.battle_name

    battle_name = models.CharField(max_length=200)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    password = models.CharField(max_length=50)

当我放下Django shell(python manage.py shell)时,我无法交互任何DateTimeField属性。

$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined

我想念什么吗?

2 个答案:

答案 0 :(得分:3)

您犯了语法错误

尝试一下

Battle.objects.filter(end_time__lt=datetime.datetime.now())

答案 1 :(得分:3)

让我添加一些解释。

Battle.objects.filter(end_time < datetime.datetime.now())

此处filter()是可调用的,它接受参数(args或kwargs)。使用以上代码,您试图将布尔值(object < object)传递给可作为参数调用的过滤器。现在,布尔值TrueFalse是否指定有关模型字段的任何内容?

您应该做的是传递关键字参数,即

Battle.objects.filter(end_time__lt=datetime.datetime.now())

现在filter()获得所需的信息,kwarg参数end_time__lt(它指定了model字段以及compare方法)以及需要与datetime.datetime.now()比较的值