Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Cannot resolve keyword 'Word' into field. Choices are:

I have find similar errors on the forum but I don't see any mistakes in my code, and models and views are really not complicated.

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)

So in my opinion Foreign Relationship should be fine. I don't have problems when I'm adding new data by admin panel. I used it in a view:

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

But I'm still getting error:

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

I don't understand why. It should send query like:

select e.* from word w join explanation e on w.word_id = e.word_foid where w.word_text = dane['Searched_word'] 

and retrieve the data.

Any ideas why it's not working properly?

like image 355
Artemise Avatar asked Jun 06 '17 21:06

Artemise


1 Answers

Your foreign key field is called word_foid, not Word. The query should use that name like this

tlumaczenie = Explanation.objects.filter(word_foid__word_text=dane['Searched_word']) 
like image 135
Daniel Roseman Avatar answered Oct 23 '22 04:10

Daniel Roseman