0

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.

1 Answer 1

1

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)) ) 
Sign up to request clarification or add additional context in comments.

3 Comments

Works. search series, authors and now books. But now something strange happens. when I look for a series that has three books for example, it prints the same series three times 127.0.0.1:8000/books/?buscar=COMANDANTE+SERVAZ prntscr.com/vv7t3w
you can try distinct() before return context docs.djangoproject.com/en/3.1/ref/models/querysets/#distinct
It's works, my friend. Thx ).distinct()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.