简体   繁体   English

不确定应该使用哪种类型的Django表单

[英]Unsure about what type of Django form I should use

I have an Author model with 200k instances in a MySQL database. 我在MySQL数据库中有一个具有200k实例的Author模型。 I want to have the user search for an Author's unique ID (which is a string) and then select an ID which will then produce a table and small graphic about that author. 我想让用户搜索作者的唯一ID(它是一个字符串),然后选择一个ID,该ID随后将生成关于该作者的表格和小图形。

Do I want to use a charfield model form? 我要使用charfield模型表格吗? Also, is there a built in search function? 另外,有内置的搜索功能吗?

I don't think Django has a builtin function for searching. 我认为Django没有内置的搜索功能。 You will have to use one of its extensions for this purpose (django-search or haystack). 为此,您将不得不使用其扩展名之一(django-search或haystack)。

They may seem too complicated for your case so I would go with simplier solution (and I would give up using form): 对于您的情况,它们似乎太复杂了,因此我将采用更简单的解决方案(而我会放弃使用表单):

from django.views.generic import ListView
from django.db.models import Q
from .models import Author

def SearchAuthorView(ListView):

  def get_queryset(self):
    name = self.request.GET['author_name']
    name_tokens = name.split(' ')

    matched_authors = []
    authors = Author.objects.all()
    for author in authors:
      for name_token in author.name.split(' '):
        if name_token in name_tokens:
          matched_authors.append(author)
          break
    return matched_authors

With 200k you may hit performance problems so if you do, you should use an optimized, raw MySql query. 如果使用200k,可能会遇到性能问题,因此,如果这样做,则应使用优化的原始MySql查询。

You may also like to order your results somehow. 您可能还希望以某种方式订购结果。 For example give lastname's match a bigger priority than firstname's match. 例如,给予“姓氏”匹配比“姓氏”匹配更高的优先级。

Honestly I don't understand the question. 老实说,我不明白这个问题。 You have a table called Author with 200k instances and you want to have possibility to find one of them. 您有一个名为Author的表,其中有200k个实例,并且希望有可能找到其中一个实例。 This can be done by simply function in views.py 只需在views.py

def search_author(request, author_id):
    author = Author.objects.get(id=author_id)
    return render_to_response('your/path/to/template', {'author': author}, RequestContext(request)) 

Then in your template you just simply display the informations: 然后,您只需在template显示以下信息:

<div class="author">
    <p>{{author.name}}</p>
    <p>{{author.image}}</p>
</div>

Of course if your models.py looks like this: 当然,如果您的models.py看起来像这样:

class Author(models.Model):
    name = models.CharField(max_number=100)
    image ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM