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

Time:05-31

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:

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"  name="q">
    </form>

CodePudding user response:

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)
)
  • Related