【问题标题】:Django - Cannot resolve keywordDjango - 无法解析关键字
【发布时间】:2014-03-30 22:01:50
【问题描述】:

我正在尝试使用以下函数在 django 视图中过滤结果:

views.py

def index(request):
    european_team_list = Team.objects.all().filter(type = 'Europe')
    context = {'european_team_list': european_team_list}
    return render(request, 'myapp/index.html', context)

admin.py

class Team(models.Model):
    continent = models.CharField()
    def _team_type(self):
        if self.country = "Europe":
            return "Europe"
        else:
            return "Not Europe"
    team_type = property(_team_type)
    ...other fields...

但是,当我加载页面时,我收到一个错误“无法将关键字 'team_type' 解析到字段中。选择是:”,然后它列出了 Team 类中除 team_type 之外的所有字段。任何指导将不胜感激。

【问题讨论】:

  • 同样if self.country = "Europe" 应该是if self.country == "Europe"
  • 您没有从此处显示的任何代码中得到该错误。请显示确切的代码,以及完整的错误和回溯。

标签: django


【解决方案1】:

简单的答案是你不能用filter() 方法来做到这一点。 filter()用于构造SQL查询,只能对数据库级别的对象进行操作。

因此,您应该弄清楚如何使用数据库值来表达您的查询。目前尚不清楚您的实际代码是什么,但它可能类似于:

european_team_list = Team.objects.filter(continent='Europe')

或:

european_team_list = Team.objects.filter(country__in=('France', 'Poland'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    相关资源
    最近更新 更多