Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why is my search function return an error Related Field got invalid lookup: category

My search function works fine but it throws me an error every time i try to search an existence post in my website. when i deleted ForeignKey in the Question model under category field the error is gone. please how can i filter that category that have a ForeignKey

the error:

FieldError at /index/
Related Field got invalid lookup: category

my models:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Category(models.Model):
    name = models.CharField(max_length=100, blank=False, null=False)

    def __str__(self):
        return str(self.name)


class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, null=False)
    body = RichTextField(blank=False, null=False) 
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, max_length=200)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Question, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.title)

the views:

def index(request):
    query = request.GET.get('q', None)
    list_of_question = Question.objects.all()
    if query is not None:
        list_of_question = Question.objects.filter(
            Q(title__icontains=query) |
            Q(category__category__icontains=query)
        )
    unread_notifications = Notification.objects.filter(user=request.user, is_read=False).count()

    paginator = Paginator(list_of_question, per_page=1)
    return render(request, 'index.html', {'unread_notifications':unread_notifications,'list_of_question':list_of_question, 'paginator':paginator})

my form:

<form action="" method="GET">
        <input placeholder="Search By Category" type="text" class="form-control" name="q">
    </form>

>Solution :

If you filter with category__… this means that the rest of the filter should deal with fields of a Category model, and a Category has a name field, so you filter with:

list_of_question = Question.objects.filter(
    Q(title__icontains=query) |
    Q(category__name__icontains=query)
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading