简体   繁体   中英

Unsure about what type of Django form I should use

I have an Author model with 200k instances in a MySQL database. 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.

Do I want to use a charfield model form? Also, is there a built in search function?

I don't think Django has a builtin function for searching. You will have to use one of its extensions for this purpose (django-search or 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.

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. This can be done by simply function in 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:

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

Of course if your models.py looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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