Python FieldError:无法将关键字“XXXX”解析为字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19145787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FieldError: Cannot resolve keyword 'XXXX' into field
提问by AlirezaJ
This is a very strange error. I only receive it on my heroku server.
这是一个非常奇怪的错误。我只在我的 heroku 服务器上收到它。
Here is how my model is:
这是我的模型:
# Abstract Model
class CommonInfo(models.Model):
active = models.BooleanField('Enabled?', default=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Country(CommonInfo):
name = models.CharField('Country Name', db_index=True, max_length=200, help_text='e.g. France')
official_name = models.CharField('Official Name', max_length=400, blank=True, help_text='e.g. French Republic')
population = models.IntegerField('Population', help_text='Population must be entered as numbers with no commas or separators, e.g. 39456123', null=True, blank=True)
alpha2 = models.CharField('ISO ALPHA-2 Code', max_length=2, blank=True)
class News(CommonInfo):
title = models.CharField('Title', max_length=250)
slug = models.CharField('slug', max_length=255, unique=True)
body = models.TextField('Body', null=True, blank=True)
excerpt = models.TextField('Excerpt', null=True, blank=True)
author = models.ForeignKey(Author)
country = models.ManyToManyField(Country, null=True, blank=True)
def __unicode__(self):
return self.title
When I try to access News items from Admin site on my production server, I get this error (everything works fine on my dev server):
当我尝试从生产服务器上的管理站点访问新闻项目时,出现此错误(在我的开发服务器上一切正常):
FieldError: Cannot resolve keyword 'news' into field. Choices are: active, alpha2, date_created, date_updated, id, name, official_name, population
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 687, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1271, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1139, in add_filter
process_extras=process_extras)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1337, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
I run the same django (1.5.4) and python (2.7.2) versions on my production and development environments.
我在生产和开发环境中运行相同的 django (1.5.4) 和 python (2.7.2) 版本。
My production server is Heroku
我的生产服务器是 Heroku
Any ideas what could triggers the error?
任何可能触发错误的想法?
UPDATE:
更新:
admin.py config is as follow:
admin.py 配置如下:
from django.contrib import admin
from APP.models import Country, News
class NewsForm(ModelForm):
class Meta:
model = News
class NewsAdmin(ModelAdmin):
form = NewsForm
search_fields = ['title',
'country__name']
list_filter = ('country',
'active'
)
list_per_page = 30
list_editable = ('active', )
list_display = ('title',
'active'
)
list_select_related = True
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Country)
admin.site.register(News, NewsAdmin)
采纳答案by AlirezaJ
Finally, I was able to resolve the issue.
最后,我能够解决这个问题。
First, I managed to replicate the error in my local environment. At first, I was testing the application using built-in Django runserver. However, my production environment is Heroku that uses Gunicorn as webserver. When I switched to Gunicorn and foreman on my local server, I was able to replicate the error.
首先,我设法在本地环境中复制了错误。起初,我使用内置的 Django runserver 测试应用程序。但是,我的生产环境是 Heroku,它使用 Gunicorn 作为网络服务器。当我在本地服务器上切换到 Gunicorn 和工头时,我能够复制错误。
Second, I tried to pin point the issue by going through the models and add/remove different components, fields. To explain the process better, I have to add a missing piece to the original question.
其次,我试图通过浏览模型并添加/删除不同的组件、字段来查明问题。为了更好地解释这个过程,我必须在原始问题中添加一个缺失的部分。
The description I had posted above is kind of incomplete. I have another model in my models.py that I did not include in my original question, because I thought it was not relevant. Here is the complete model:
我上面发布的描述有点不完整。我的models.py中有另一个模型,我没有包含在我的原始问题中,因为我认为它不相关。这是完整的模型:
# Abstract Model
class CommonInfo(models.Model):
active = models.BooleanField('Enabled?', default=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Country(CommonInfo):
name = models.CharField('Country Name', db_index=True, max_length=200, help_text='e.g. France')
official_name = models.CharField('Official Name', max_length=400, blank=True, help_text='e.g. French Republic')
population = models.IntegerField('Population', help_text='Population must be entered as numbers with no commas or separators, e.g. 39456123', null=True, blank=True)
alpha2 = models.CharField('ISO ALPHA-2 Code', max_length=2, blank=True)
def get_country_names():
names = Country.objects.only('name').filter(active=1)
names = [(str(item), item) for item in names]
return names
class Person(CommonInfo):
name = models.CharField(max_length=200)
lastname = models.CharField(max_length=300)
country = models.CharField(max_length=250, choices=choices=get_country_names())
class News(CommonInfo):
title = models.CharField('Title', max_length=250)
slug = models.CharField('slug', max_length=255, unique=True)
body = models.TextField('Body', null=True, blank=True)
excerpt = models.TextField('Excerpt', null=True, blank=True)
author = models.ForeignKey(Author)
country = models.ManyToManyField(Country, null=True, blank=True)
def __unicode__(self):
return self.title
My model design didn't require a ForeignKey for Person's table, so I had decided to go with a simple CharField and instead, use a regular drop down menu. However, for some reason, Gunicorn raises the above mentioned error when, as part of the get_country_names(), the Country table is called before News. As soon as I deleted the get_country_names() and turned the country field on Person table into a regular CharField the issue was resolved.
我的模型设计不需要 Person 表的外键,所以我决定使用简单的 CharField,而是使用常规下拉菜单。然而,由于某种原因,当作为 get_country_names() 的一部分,Country 表在 News 之前被调用时,Gunicorn 会引发上述错误。一旦我删除了 get_country_names() 并将 Person 表上的 country 字段转换为常规 CharField ,问题就解决了。
Reading through the comments in this old Django bugand this postby Chase Seibert considerably helped me in this process.
通读这个旧 Django 错误中的评论和Chase Seibert 的这篇文章在这个过程中对我有很大帮助。
Although ticket#1796 appears to be fixed more than 6 years ago, it seems that some tiny issues still remain deep buried there.
尽管票号#1796 似乎在 6 年前就已修复,但似乎一些小问题仍然深埋在那里。
Thats it! Thanks everyone.
就是这样!谢谢大家。
回答by Cameron
I'd had some ManyToMany relationships that were working one-way. I had been messing around with my settings and changing the name of the main application a couple times. Somewhere along the lines, I had removed it from the INSTALLED_APPS
section! Once I added that back in, then it worked. Definitely PEBKAC, but maybe this will help someone some day. It took me a while to think of checking for that, since the app was mostly working.
我曾经有过一些单向工作的多对多关系。我一直在搞乱我的设置并更改了主应用程序的名称几次。沿着这条线的某个地方,我已将其从该INSTALLED_APPS
部分中删除!一旦我把它加回来,它就起作用了。绝对是 PEBKAC,但也许有一天这会对某人有所帮助。我花了一段时间才考虑检查这一点,因为该应用程序大部分时间都在运行。
For example, my app is called deathvalleydogs
. I had two models:
例如,我的应用程序名为deathvalleydogs
. 我有两个模型:
class Trip(ModelBase):
dogs = models.ManyToManyField(Dog, related_name="trips")
class Dog(ModelBase):
name = models.CharField(max_length=200)
when I tried to show a template for a Trip
listing the Dogs
that were on the trip like this:
当我尝试显示旅行中的Trip
清单模板时,Dogs
如下所示:
{% for dog in trip.dogs.all %}
<li><a href="/dogs/{{ dog.id }}">{{ dog.name }}</a></li>
{% endfor %}
then I got an error of:
然后我得到了一个错误:
Cannot resolve keyword u'trips' into field. Choices are: active, birth_date, ...
Though I was still able to show a template for a Dog
listing the trips they were on. Notice that trips
should have been a field created by the m2m on the Dog
objects. I wasn't referencing that field in the template, but it barfed on that field anyway in debug mode.
虽然我仍然能够显示一个模板来Dog
列出他们所进行的旅行。请注意,这trips
应该是 m2m 在Dog
对象上创建的字段。我没有在模板中引用该字段,但它在调试模式下无论如何都会在该字段上显示。
I wish the error had been more explicit, but I'm just so happy I finally found my mistake!!!
我希望错误更明确,但我很高兴我终于找到了我的错误!!!
回答by Jj.
Adding to the possible situations under which this happens. I searched for the field that could not be found in any of my models.
添加到发生这种情况的可能情况。我搜索了在我的任何模型中都找不到的字段。
Searching on the code I found that I was annotating a queryset with such field and then feeding that queryset as an __in
search to another (along other complex queries).
搜索代码我发现我正在用这样的字段注释一个查询集,然后将该__in
查询集作为搜索提供给另一个(以及其他复杂的查询)。
My work around was to change that annotated queryset to return IDs and use that. On this particular case that result was always going to be small so the list of IDs was not a problem to pass.
我的解决方法是更改带注释的查询集以返回 ID 并使用它。在这种特殊情况下,结果总是很小,因此通过 ID 列表不是问题。
回答by Alexei Marinichenko
You can try to reset migrations:
您可以尝试重置迁移:
- Remove the all migrations files within your project. Go through each of your projects apps migration folder (your_app/migrations/) and remove everything inside, except the init.py file.
- Run
makemigrations
andmigrate
.
- 删除项目中的所有迁移文件。浏览您的每个项目应用程序迁移文件夹 ( your_app/migrations/) 并删除里面的所有内容,除了init.py 文件。
- 运行
makemigrations
和migrate
。
回答by jmunsch
I was using the wrong dunder lookup on an admin model search field, so for example:
我在管理模型搜索字段上使用了错误的 dunder 查找,例如:
Not working:
不工作:
class SomeAdmin(admin.ModelAdmin):
list_display = (
"id",
"thing_id",
"count",
"stuff_name",
"stuff_id"
)
readonly_fields = ("count")
# These cannot be resolved, because "stuff" doesn't exist on the model
search_fields = ("stuff__name", "stuff__id")
def stuff_name(self, obj):
return obj.thing.stuff.name
def stuff_id(self, obj):
return obj.thing.stuff.id
def get_queryset(self, request):
return super().get_queryset(request).select_related("thing")
Working:
在职的:
class SomeAdmin(admin.ModelAdmin):
list_display = (
"id",
"thing_id",
"count",
"stuff_name",
"stuff_id"
)
readonly_fields = ("count")
search_fields = ("thing__stuff__name", "thing__stuff__id", "thing__id")
def stuff_name(self, obj):
return obj.thing.stuff.name
def stuff_id(self, obj):
return obj.thing.stuff.id
def get_queryset(self, request):
return super().get_queryset(request).select_related("thing")
回答by KingNonso
I had this error. And if your are using POSTMAN to do an API call to a URL, then you may be encountering this same error.
我有这个错误。如果您使用 POSTMAN 对 URL 进行 API 调用,那么您可能会遇到同样的错误。
django.core.exceptions.FieldError: Cannot resolve keyword 'player' into field. Choices are ...
django.core.exceptions.FieldError:无法将关键字“玩家”解析为字段。选择是...
Either in your model or serializer, you are referring to a particular field e.g. player
in my case as you would when it is referenced as a foreign key.
在您的模型或序列化程序中,您指的是特定字段,例如player
在我的情况下,就像将其作为外键引用一样。
In my case I had a Player model, and I wanted to update the reference in the save method of a Market model, when a weight is changed in the market, it should reflect immediately on the player.
在我的例子中,我有一个 Player 模型,我想更新 Market 模型的 save 方法中的引用,当市场中的权重发生变化时,它应该立即反映在玩家身上。
class Market(models.Model):
player = models.ForeignKey(Player)
weight = models.CharField('Weight')
...
def save(self):
if self.weight:
# wrong
Player.objects.get(player=self.player) # this object reference of itself does not exist, hence the error
# right
Player.objects.get(pk=self.player.pk)
...
super().save()