【问题标题】:Django Cannot resolve keyword 'Word' into field. Choices are:Django 无法将关键字“Word”解析为字段。选择是:
【发布时间】:2017-11-08 01:48:08
【问题描述】:

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

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)

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

views.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})

但我仍然收到错误:

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'] 

并检索数据。

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

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

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

    tlumaczenie = Explanation.objects.filter(word_foid__word_text=dane['Searched_word']) 
    

    【讨论】:

    • 但我不知道 word_id。当我继续我的观点时,我只有 word_text。我想我所做的就像文档显示的那样:“D​​jango 提供了一种强大且直观的方式来“跟踪”查找中的关系,在幕后自动为您处理 SQL JOIN。要跨越关系,只需使用跨模型的相关字段的字段名称,用双下划线分隔,直到找到您想要的字段。此示例检索名称为“Beatles Blog”的 Blog 的所有 Entry 对象: >>> Entry.objects.filter(blog__name= '披头士博客')"
    • Explanation.objects.filter(word_foid__word_text=dane['Searched_word']) 就是你要找的东西
    猜你喜欢
    • 2014-04-15
    • 2016-05-10
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2021-11-18
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多