Reputation: 47
I am a kind of new to Django. And I am setting up a project that can display quotes based on a specific author or writer. I am having trouble creating the search function to display quotes based on the author's name. How do I create a search view function and display it on the template.
For example, the user searches the author name from author_name in class Author, then it displays a list of quotes by the author
Below is a sample of my models.py file
class Author(models.Model):
author_name = models.CharField(max_length=50)
id = models.AutoField(primary_key=True)
description = models.TextField(max_length=500)
portrait = models.ImageField()
def __str__(self):
return self.author_name
class Quote(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
quote = models.TextField(max_length=500)
def __str__(self):
return self.quote
Upvotes: 1
Views: 131
Reputation: 477533
For a given author_name
, you can look up the Quote
s of that author with:
Quote.objects.filter(author__author_name=author_name)
You might want to use the __icontains
lookup [Django-doc], since this will match Alexander Pope
, given you search for pope
, or alex
:
Quote.objects.filter(author__author_name__icontains=author_name)
Upvotes: 1