【问题标题】:How to implement a search function in django如何在django中实现搜索功能
【发布时间】:2019-11-20 01:07:20
【问题描述】:

我是 Django 的新手。我正在建立一个可以根据特定作者或作家显示报价的项目。我在创建搜索功能以根据作者姓名显示引号时遇到问题。如何创建搜索视图功能并将其显示在模板上。

例如,用户从 Author 类中的 author_name 中搜索作者姓名,然后显示作者的引用列表

以下是我的 models.py 文件的示例

类作者(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

类引用(models.Model):

author = models.ForeignKey(Author, on_delete=models.CASCADE)
quote = models.TextField(max_length=500)

def __str__(self):
    return self.quote

【问题讨论】:

    标签: django django-models django-forms django-views


    【解决方案1】:

    对于给定的author_name,您可以通过以下方式查找该作者的Quotes:

    Quote.objects.filter(<b>author__author_name=<i>author_name</i></b>)

    您可能想要使用__icontains lookup [Django-doc],因为如果您搜索popealex,这将匹配Alexander Pope

    Quote.objects.filter(author__author_name<b>__icontains</b>=<i>author_name</i>)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多