Drennos
Drennos

Reputation: 313

Filter queryset for foreign key

I need to filter the books associated with my serie model

My models.py

class Serie(models.Model):
    serie = models.CharField(max_length = 255)
    author = models.ForeignKey(Author, on_delete = models.CASCADE, null = True)
    slug = AutoSlugField(populate_from = 'serie', always_update = True)

class Book(models.Model):
    serie = models.ForeignKey(Serie, on_delete = models.CASCADE, null = True)
    serie_slug = AutoSlugField(populate_from = 'serie', always_update = True, null = True)
    book_title = models.CharField(max_length=200)
    slug = AutoSlugField(populate_from = 'book_title', always_update = True, null = True)
    resume = RichTextField()
    pub_date = models.DateTimeField(auto_now_add = True, null = True)

My views.py

class index(ListView):
    model = Serie
    template_name = 'serie_book_list.html'
    ordering = ['id']

    def get_queryset(self, *args, **kwargs):
        context = super().get_queryset(*args, **kwargs)
        search = self.request.GET.get('buscar', None)

        if search:
            context = context.filter(
                Q(serie__icontains = search) |
                Q(author__name__icontains = search) |
                Q(Book.objects.filter(book_title__icontains = search))
            )
        return context

I tried to use this code Q(Book.objects.filter(book_title__icontains = search)), but without success.

Cannot filter against a non-conditional expression.

Upvotes: 0

Views: 719

Answers (1)

Ngoc Pham
Ngoc Pham

Reputation: 1458

your filter Q(Book.objects.filter(book_title__icontains = search)) not match any field in Serie

try this:

context = context.filter(
            Q(serie__icontains=search) |
            Q(author__name__icontains=search) |
            Q(book__book_title__icontains=search))
        )

Upvotes: 1

Related Questions