2017-06-06 45 views
0

我在論壇上發現類似的錯誤,但我沒有看到我的代碼中有任何錯誤,模型和視圖真的不復雜。Django無法將關鍵字'Word'解析爲字段。選擇是:

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: Cannot resolve keyword 'Word' into field. Choices are: 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'] 

並檢索數據。

任何想法爲什麼它不能正常工作?

回答

2

您的外鍵字段被稱爲word_foid,而不是Word。查詢應該使用像這樣的名稱

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

但我不知道word_id。當我繼續我的觀點時,我只有word_text。我想我就像文檔顯示它一樣:「Django提供了一種強大而直觀的方式來在查找中」追蹤「關係,在後臺自動爲您處理SQL JOIN。要跨越關係,只需使用字段名稱跨模型的相關字段,用雙下劃線分隔,直到您到達您想要的字段。 本示例使用名爲'Beatles Blog'的博客檢索所有Entry對象: >>> Entry.objects。過濾器(blog__name ='披頭士博客')「 – Artemise

+0

'Explanation.objects.filter(word_foid__word_text = dane ['Searched_word'])'是你要找的東西 – Brobin

相關問題