如何搜索数据库并打印结果?

时间:2018-06-19 23:47:37

标签: python django

我要做的是使它可以直接搜索数据库,而无需在搜索页面上看到整个数据库。搜索页面应该为空。您进行搜索,它会直接转到与您的搜索条件匹配的数据库条目的详细信息页面。如果没有匹配项,则显示“找不到匹配项”。我该怎么办?

这是我到目前为止所拥有的。这会在与我的搜索框相同的页面上打印/列出数据库中的每个条目,完成搜索后,列表将被缩减为与搜索条件匹配的条目。每个数据库条目都有一个链接,您可以单击该链接将您带到一个详细信息页面,该页面将提取该条目的信息。

我正在使用Django 2.0。

Manage.py

2018-06-19 14:23:14 0
2018-06-19 14:23:16 0
2018-06-19 14:23:27 1
2018-06-19 14:23:28 1
2018-06-19 14:23:29 1

Views.py

class PostManager(models.Manager): 
    def active(self, *args, **kwargs):
        return super(PostManager, self).filter(draft=False).filter(publish__lte=timezone.now())

def upload_location(instance, filename):                
    return "%s/%s" %(instance.slug, filename)               

class Remote(models.Model):
    brand = models.CharField(max_length=20)
    model = models.CharField(max_length=25)
    type = models.CharField(max_length=50)
    orig = models.TextField()
    comp = models.TextField(blank=True)
    image = models.ImageField(upload_to=upload_location,
    null=True, blank=True, default=0,
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, default=1)
slug = models.SlugField(unique=True)
objects = PostManager() 

def __str__(self):
    return self.model

def get_absolute_url(self):
    return reverse("mainapp:detail", kwargs={"slug": self.slug})

def create_slug(instance, new_slug=None):
    slug = slugify(instance.model) #slugify title
    if new_slug is not None:
        slug = new_slug
    qs = Remote.objects.filter(slug=slug).order_by("-id") 
    exists = qs.exists() 
    if exists: 
        new_slug = "%s-%s" %(slug, qs.first().id) 
    return create_slug(instance, new_slug=new_slug)
    return slug 

def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Remote)

用于Remote_list视图的HTML

def detail(request, slug=None):
    instance = get_object_or_404(Remote, slug=slug)
    share_string = quote_plus(instance.orig)
    context={
        "model": instance.model,
        "instance": instance, 
        "share_string": share_string,
    }
return render(request, 'mainapp/remote_detail.html', context)

def remote_list(request):
    today = timezone.now().date()
    queryset_posts = Remote.objects.all()
    if request.user.is_staff or request_user_is_superuser:
        queryset_posts = Remote.objects.all()

query = request.GET.get("q") # search stuff
    if query:
        queryset_posts = queryset_posts.filter(
            Q(model__icontains=query)|      
            Q(orig__icontains=query)    
            ).distinct() #.distinct() doesn't allow duplicates to show up

paginator = Paginator(queryset_posts,10) # Show 25 contacts per page
page_request_var = "pagina" #this changes "Page name in pagination
page = request.GET.get(page_request_var)
queryset = paginator.get_page(page)

context={
    "object_list": queryset,
    "title": "List",
    "page_request_var": page_request_var,
    "today": today,
}
return render(request, 'mainapp/remote_list.html', context)

“ HTML for Detail”视图

    <form class='mb-2' method='GET' action=''>
    <input type='text' name='q' placeholder='Search posts' value='{{  request.GET.q }}'/> 
    <input href='{{ obj.get_absolute_url }}' type='submit' value='Search'/>
    </form>
{% for obj in object_list %}
{% if obj.image %}
    <img class="card-img-top" src="{{ obj.image.url }}" alt="Image" style="max-width:100px;">
{% endif %}  

<h5 class="card-title"><a href='{{ obj.get_absolute_url }}'>{{ obj.model }}</a></h5>
{% if obj.user.get_full_name %}
<p>Author: {{ obj.user.get_full_name }}</p>
{% endif %}
<p class="card-text">{{ obj.orig|truncatechars:120 }}</p>
<a href="{{ obj.get_absolute_url }}" class="btn btn-primary">View</a>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

您需要向您的qs添加一些代码,但是现在没问题了 如果您的模型包含标题字段,则您需要了解有关过滤查询并将其传递给视图的更多信息,您可以在模板中使用{_ your_data.title}}做为your_data是过滤后的传递查询