Django 无法将关键字“Word”解析为字段。选择是:

Art*_*ise 6 django django-models django-views

我在论坛上发现了类似的错误,但我没有看到我的代码中有任何错误,而且模型和视图并不复杂。

class Word(models.Model):

    word_text = models.CharField(max_length=50)
    user_crea = models.CharField(max_length=20)
    publ_date = models.DateTimeField(auto_now_add=True)
    modi_date = models.DateTimeField(auto_now=True)


class Explanation(models.Model):

    word_foid = models.ForeignKey(Word, on_delete=models.CASCADE)
    expl_text = models.CharField(max_length=50)
    user_crea = models.CharField(max_length=20)
    publ_date = models.DateTimeField(auto_now_add=True)
    modi_date = models.DateTimeField(auto_now=True)
Run Code Online (Sandbox Code Playgroud)

所以在我看来外交关系应该没问题。通过管理面板添加新数据时没有问题。我在一个视图中使用它:

视图.py

def index(request):
    if request.method == 'POST':
        form = Search(request.POST)
        if form.is_valid():
            dane = form.cleaned_data
            tlumaczenie=Explanation.objects.filter(Word__word_text=dane['Searched_word'])
            print(tlumaczenie)
            return render(request,'explanation.html', {'dane':dane})
Run Code Online (Sandbox Code Playgroud)

但我仍然收到错误:

django.core.exceptions.FieldError:无法将关键字“Word”解析为字段。选项有:expl_text、id、modi_date、publ_date、user_crea、word_foid、word_foid_id

我不明白为什么。它应该发送如下查询:

select e.* from word w join explanation e on w.word_id = e.word_foid where w.word_text = dane['Searched_word'] 
Run Code Online (Sandbox Code Playgroud)

并检索数据。

任何想法为什么它不能正常工作?

Dan*_*man 5

您的外键字段被称为word_foid,而不是Word。查询应该像这样使用该名称

tlumaczenie = Explanation.objects.filter(word_foid__word_text=dane['Searched_word']) 
Run Code Online (Sandbox Code Playgroud)