/ search /中的django FieldError无法解析关键字'searchkeyword'

时间:2011-11-11 05:06:25

标签: django filter foreign-keys django-queryset

我正在通过Practical Django Projects的书工作,我很难过。这本书适用于早期版本的Django。我正在使用v1.3。

问题在视图中,在'search_ 关键字 _keyword__in ...'

from django.contrib.flatpages.models import FlatPage
from django.shortcuts import render_to_response

def search(request):
    query = request.GET.get('q', '') 
    keyword_results = results = []
    if query:
        keyword_results = FlatPage.objects.filter(searchkeyword__keyword__in=query.split()).distinct()
        results = FlatPage.objects.filter(content__icontains=query)
    return render_to_response('search/search.html',
                    {'query' : query,
                     'keyword_results': keyword_results,
                     'results' : results })

models.py是

from django.contrib.flatpages.models import FlatPage
from django.db import models

class SearchKeyword(models.Model):
    keyword = models.CharField(max_length=50)
    page = models.ForeignKey(FlatPage)

    def __unicode__(self):
        return self.keyword

完整错误是:

Cannot resolve keyword 'searchkeyword' into field. Choices are: content, enable_comments, id, registration_required, sites, template_name, title, url

我认为FlatPages的选项。似乎没有找到外键关系。

任何想法可能是错误的或如何正确地进行查找?感谢。

以下是admin.py,以防它有一些方法:

from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib import admin
from cms.search.models import SearchKeyword
from django.contrib.flatpages.models import FlatPage

# Define an inline admin descriptor for SearchKeywords model
class SearchKeywordInline(admin.TabularInline):
    model = SearchKeyword

# Define a FlatPageAdmin class
class ExtendedFlatPageAdmin(FlatPageAdmin):
    inlines = [
        SearchKeywordInline,
    ]

# Re-register FlatPageAdmin
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, ExtendedFlatPageAdmin)

2 个答案:

答案 0 :(得分:0)

ForeignKey的反向关系将命名为searchkeyword_set(请参阅https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects),因此您的查询集应该有searchkeyword_set__keyword__in作为参数(或者您可以使用related_name。

如果这不起作用,你应该检查你是否已经完成了manage.py syncdb?

答案 1 :(得分:0)

似乎问题是:

from django.contrib.flatpages.models import FlatPage
from django.db import models

模型需要先行,如:

from django.db import models
from django.contrib.flatpages.models import FlatPage

我认为发生的事情是在创建ForeignKey之前创建了FlatPage实例,因此FlatPage无法使用SearchKeyword属性。