我使用Django为足球俱乐部建立一个网站,其中包含许多博客文章。我试图加入搜索栏,但我无法使其发挥作用。提交搜索词时,会显示以下错误:
在/ web / search /
中不存在 Articulo匹配查询不存在。
这是我的代码:
def search(request):
query = request.GET.get('q', '')
if query:
try:
qset = (
Articulo(titulo__icontains=query) |
Articulo(cuerpo_icontains=query)
)
results = Articulo.objects.filter(qset).distinct()
except Articulo.DoesNotExist:
results = None
else:
results = []
return render_to_response('web/buscar.html', {"results": results, "query": query})
<div id="busqueda" class="row">
<div class="col-md-12">
<span id="cruz" class="fas fa-times fa-2x"></span>
<form method="GET" action="/web/search/" class="form my-2 my-lg-0">
<input id="searchBox" value="{{ query|escape }}" class="form-control mr-sm-2" type="text" name="q" placeholder="Buscar" aria-label="Buscar">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Buscar</button>
</form>
</div>
</div>
url(r'^search/$', search),
class Articulo(models.Model):
"""Un artículo de la página"""
id = models.AutoField(primary_key=True)
titulo = models.CharField(max_length=100)
slug = models.SlugField(unique=True, default="")
CATEGORIAS = (
('Primera y Sub 21', 'Primera y Sub 21'),
('Inferiores', 'Inferiores'),
('Básquet', 'Básquet'),
('Hockey', 'Hockey'),
('Gurises', 'Gurises'),
('Generales', 'Generales'),
('Institucionales', 'Institucionales'),
('Senior', 'Senior'),
)
categoria = models.CharField(
max_length=200,
choices=CATEGORIAS
)
cuerpo = RichTextField()
fecha_hora= models.DateTimeField()
foto = models.ImageField()
url_video = models.CharField(help_text='Url del video de facebook (opcional). Para obtener el link, ir al video, apretar donde están los 3 puntitos y poner "insertar". Pegar aquí solo el link del video, borrar el resto. Ejemplo: https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FJuanCruzPiornoOficial%2Fvideos%2F302760100205413', max_length=500,blank=True)
album_flickr = models.CharField(help_text="Subir fotos a Flickr, crear un álbum, compartirlo eligiendo la opción 'Insertar', elegir el tamaño más grande, y pegar el link aquí", max_length=700, blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.titulo)
super(Articulo, self).save(*args, **kwargs)
def __str__(self):
return self.titulo
答案 0 :(得分:0)
首先你需要导入Q之后你可以查找带有关键字参数的函数(例如filter(),exclude(),get()
from django.db.models import Q
def search(request):
query = request.GET.get('q', '')
if query:
Articulo.objects.get(
Q(titulo__icontains=query) |
Q(cuerpo_icontains=query)
)
return query
有关详情,请查看文档here
答案 1 :(得分:0)
from django.db.models import Q
def search(request):
results = []
query = request.GET.get('q', None)
if query:
try:
results = Articulo.objects.filter(Q(titulo__icontains=query) | Q(cuerpo_icontains=query))
except Articulo.DoesNotExist:
pass
return render_to_response('web/buscar.html',{"results": results, "query": query})
答案 2 :(得分:0)
试试这个
def search(request):
query = request.GET.get('q', '')
if query:
try:
qset = Articulo.objects.filter(Q(titulo__icontains=query) | cuerpo_icontains = query) # change is here <<
results = Articulo.objects.filter(some_field=some_value).distinct() # change is here <<
except Articulo.DoesNotExist:
results = None
else:
results = []
return render_to_response('web/buscar.html', {"results": results, "query": query})
注意:我不确定您为何使用qset
和result
!
答案 3 :(得分:0)
由于您尝试执行“搜索”(或过滤),您应该使用“fitler()”而不是get(),它在语义上更有意义。对于您的信息,如果结果为空,则过滤器不会引发异常。 您的代码看起来类似于:
ListView
如果您使用from django.db.models import Q
def search(request):
results = []
query = request.GET.get('q', '')
if query:
qset = Q(titulo__icontains=query) | Q(cuerpo__icontains=query)
results = Articulo.objects.filter(qset).distinct()
ctx = {"results": results, "query": query}
return render_to_response('web/buscar.html', ctx)
的代码获得DoesNotExist
个例外,则应查看回溯以查找li filter()
文件,以确保调用所需的视图而不是其他人。