SlideShare a Scribd company logo
Searching Django
 
The Model: class Issue(models.Model): title = models.CharField(max_length=250) description = models.TextField(blank=True) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) date_completed = models.DateTimeField(null=True, blank=True) creator = models.ForeignKey(User, related_name="issue_creator") owner = models.ForeignKey(User, related_name="issue_owner", null=True, blank=True) stakeholders = models.ManyToManyField(User, related_name="issue_stakeholders", null=True, blank=True) date_due = models.DateTimeField(null=True, blank=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='new') urgency = models.ForeignKey(Urgency, related_name="issue_urgency", null=True, blank=True) importance = models.ForeignKey(Importance, related_name="issue_importance", null=True, blank=True) visible = models.BooleanField(default=True) order = models.IntegerField(blank=True, null=True)
The Form: class SearchForm(forms.Form): """ Allows user to search for Issues based on certain criteria, none required, most found in Issue model """ keywords = forms.CharField(help_text='Keyword search of issue title and description', required=False) date_added = forms.DateTimeField(help_text='Date issue was created', required=False) date_modified = forms.DateTimeField(help_text='Date issue was last modified', required=False) date_completed = forms.DateTimeField(help_text='Date issue was closed', required=False) date_due = forms.DateTimeField(help_text='Date issue is due', required=False) status = forms.ChoiceField(choices=STATUS_CHOICES, required=False) urgency = forms.ModelChoiceField(queryset=Urgency.objects.all(), required=False) importance = forms.ModelChoiceField(queryset=Importance.objects.all(), required=False) creator = forms.ModelChoiceField(queryset=User.objects.all(), required=False) owner = forms.ModelChoiceField(queryset=User.objects.all(), required=False) stakeholder = forms.ModelChoiceField(queryset=User.objects.all(), required=False)
The search view: def issues_search(request, form_class=SearchForm, template_name='search.html'): form = None if request.method == 'POST': #do search form = form_class(request.POST) if form.is_valid(): results = search(form.cleaned_data) if results: return render_to_response(template_name, {'form': form, 'issues': results}) else: form = form_class() return render_to_response(template_name, {'form': form})
Search: def search(search_data): q = Q() results = None searcher = IssueSearch(search_data) for key in search_data.iterkeys(): dispatch = getattr(searcher, 'search_%s' % key) q = dispatch(q) if q and len(q): results = Issue.objects.filter(q).select_related() #.order_by('-pk') else: results = [] return results
Searcher: class IssueSearch(object): def __init__(self, search_data): self.__dict__.update(search_data) def search_keywords(self, q): """ Search should do both title and description, and OR the results together, and must iterate over list of keywords """ if self.keywords: words = self.keywords.split() title_q = Q() desc_q = Q() for word in words: title_q = title_q | Q(title__icontains=word) desc_q = desc_q | Q(description__icontains=word) keyword_q = title_q | desc_q q = q & keyword_q return q def search_date_added(self, q): if self.date_added: q = q & Q(date_added__exact=self.date_added) return q
Searcher, part 2: def search_owner(self, q): if self.owner: q = q & Q(owner__icontains=self.owner) return q def search_stakeholder(self, q): if self.stakeholder:  if isinstance(self.stakeholder, list): q = q & Q(stakeholder__in=self.stakeholder) else: q = q & Q(stakeholder__icontains=self.stakeholder) return q
Questions?

More Related Content

PPTX
Web осень 2012 лекция 7
PPTX
Working With JQuery Part1
PPTX
Web весна 2013 лекция 7
PPTX
Django tips and_tricks (1)
PDF
Python 3.x Dictionaries and Sets Cheatsheet
PPTX
Scala best practices
ODP
Javascript & jQuery: A pragmatic introduction
KEY
Jython: Python para la plataforma Java (JRSL 09)
Web осень 2012 лекция 7
Working With JQuery Part1
Web весна 2013 лекция 7
Django tips and_tricks (1)
Python 3.x Dictionaries and Sets Cheatsheet
Scala best practices
Javascript & jQuery: A pragmatic introduction
Jython: Python para la plataforma Java (JRSL 09)

What's hot (18)

PDF
The Ring programming language version 1.6 book - Part 35 of 189
PDF
The Ring programming language version 1.5.2 book - Part 33 of 181
PPTX
Drupal7 dbtng
PDF
The Art of Transduction
PDF
Fp java8
PDF
The Ring programming language version 1.6 book - Part 24 of 189
PDF
High Performance GPU computing with Ruby, Rubykaigi 2018
PPTX
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
PDF
Odoo - From v7 to v8: the new api
PDF
Django
PDF
C++ prgms 3rd unit
PDF
Swift에서 꼬리재귀 사용기 (Tail Recursion)
PDF
The Ring programming language version 1.5.4 book - Part 22 of 185
PPT
An Elephant of a Different Colour: Hack
PPTX
6. CodeIgniter copy2
PDF
The Ring programming language version 1.5.3 book - Part 44 of 184
PDF
The Ring programming language version 1.9 book - Part 41 of 210
The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.5.2 book - Part 33 of 181
Drupal7 dbtng
The Art of Transduction
Fp java8
The Ring programming language version 1.6 book - Part 24 of 189
High Performance GPU computing with Ruby, Rubykaigi 2018
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
Odoo - From v7 to v8: the new api
Django
C++ prgms 3rd unit
Swift에서 꼬리재귀 사용기 (Tail Recursion)
The Ring programming language version 1.5.4 book - Part 22 of 185
An Elephant of a Different Colour: Hack
6. CodeIgniter copy2
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.9 book - Part 41 of 210
Ad

Similar to Django Search (20)

PPT
Moodle Quick Forms
PPT
Django Forms: Best Practices, Tips, Tricks
PPTX
Custom Signals for Uncoupled Design
PPTX
PyCon APAC - Django Test Driven Development
PDF
Crowdsourcing with Django
PDF
Django design-patterns
PPTX
Lo nuevo de Django 1.7 y 1.8
ODP
Pruebas unitarias con django
PDF
WTF Oriented Programming, com Fabio Akita
PDF
A brief history of Django model syntax
PDF
날로 먹는 Django admin 활용
KEY
Advanced Django ORM techniques
KEY
Django Admin: Widgetry & Witchery
ODP
Django tech-talk
PDF
Optimization in django orm
KEY
Jython: Python para la plataforma Java (EL2009)
PDF
The Ring programming language version 1.8 book - Part 50 of 202
PDF
Django Heresies
KEY
CoffeeScript - A Rubyist's Love Affair
ODP
Scala introduction
Moodle Quick Forms
Django Forms: Best Practices, Tips, Tricks
Custom Signals for Uncoupled Design
PyCon APAC - Django Test Driven Development
Crowdsourcing with Django
Django design-patterns
Lo nuevo de Django 1.7 y 1.8
Pruebas unitarias con django
WTF Oriented Programming, com Fabio Akita
A brief history of Django model syntax
날로 먹는 Django admin 활용
Advanced Django ORM techniques
Django Admin: Widgetry & Witchery
Django tech-talk
Optimization in django orm
Jython: Python para la plataforma Java (EL2009)
The Ring programming language version 1.8 book - Part 50 of 202
Django Heresies
CoffeeScript - A Rubyist's Love Affair
Scala introduction
Ad

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
A Presentation on Artificial Intelligence
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
Machine Learning_overview_presentation.pptx
PDF
Encapsulation theory and applications.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Building Integrated photovoltaic BIPV_UPV.pdf
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
Programs and apps: productivity, graphics, security and other tools
Per capita expenditure prediction using model stacking based on satellite ima...
A comparative study of natural language inference in Swahili using monolingua...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation_ Review paper, used for researhc scholars
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Heart disease approach using modified random forest and particle swarm optimi...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Diabetes mellitus diagnosis method based random forest with bat algorithm
TLE Review Electricity (Electricity).pptx
A Presentation on Artificial Intelligence
cloud_computing_Infrastucture_as_cloud_p
Machine Learning_overview_presentation.pptx
Encapsulation theory and applications.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...

Django Search

  • 2.  
  • 3. The Model: class Issue(models.Model): title = models.CharField(max_length=250) description = models.TextField(blank=True) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) date_completed = models.DateTimeField(null=True, blank=True) creator = models.ForeignKey(User, related_name="issue_creator") owner = models.ForeignKey(User, related_name="issue_owner", null=True, blank=True) stakeholders = models.ManyToManyField(User, related_name="issue_stakeholders", null=True, blank=True) date_due = models.DateTimeField(null=True, blank=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='new') urgency = models.ForeignKey(Urgency, related_name="issue_urgency", null=True, blank=True) importance = models.ForeignKey(Importance, related_name="issue_importance", null=True, blank=True) visible = models.BooleanField(default=True) order = models.IntegerField(blank=True, null=True)
  • 4. The Form: class SearchForm(forms.Form): """ Allows user to search for Issues based on certain criteria, none required, most found in Issue model """ keywords = forms.CharField(help_text='Keyword search of issue title and description', required=False) date_added = forms.DateTimeField(help_text='Date issue was created', required=False) date_modified = forms.DateTimeField(help_text='Date issue was last modified', required=False) date_completed = forms.DateTimeField(help_text='Date issue was closed', required=False) date_due = forms.DateTimeField(help_text='Date issue is due', required=False) status = forms.ChoiceField(choices=STATUS_CHOICES, required=False) urgency = forms.ModelChoiceField(queryset=Urgency.objects.all(), required=False) importance = forms.ModelChoiceField(queryset=Importance.objects.all(), required=False) creator = forms.ModelChoiceField(queryset=User.objects.all(), required=False) owner = forms.ModelChoiceField(queryset=User.objects.all(), required=False) stakeholder = forms.ModelChoiceField(queryset=User.objects.all(), required=False)
  • 5. The search view: def issues_search(request, form_class=SearchForm, template_name='search.html'): form = None if request.method == 'POST': #do search form = form_class(request.POST) if form.is_valid(): results = search(form.cleaned_data) if results: return render_to_response(template_name, {'form': form, 'issues': results}) else: form = form_class() return render_to_response(template_name, {'form': form})
  • 6. Search: def search(search_data): q = Q() results = None searcher = IssueSearch(search_data) for key in search_data.iterkeys(): dispatch = getattr(searcher, 'search_%s' % key) q = dispatch(q) if q and len(q): results = Issue.objects.filter(q).select_related() #.order_by('-pk') else: results = [] return results
  • 7. Searcher: class IssueSearch(object): def __init__(self, search_data): self.__dict__.update(search_data) def search_keywords(self, q): """ Search should do both title and description, and OR the results together, and must iterate over list of keywords """ if self.keywords: words = self.keywords.split() title_q = Q() desc_q = Q() for word in words: title_q = title_q | Q(title__icontains=word) desc_q = desc_q | Q(description__icontains=word) keyword_q = title_q | desc_q q = q & keyword_q return q def search_date_added(self, q): if self.date_added: q = q & Q(date_added__exact=self.date_added) return q
  • 8. Searcher, part 2: def search_owner(self, q): if self.owner: q = q & Q(owner__icontains=self.owner) return q def search_stakeholder(self, q): if self.stakeholder: if isinstance(self.stakeholder, list): q = q & Q(stakeholder__in=self.stakeholder) else: q = q & Q(stakeholder__icontains=self.stakeholder) return q

Editor's Notes

  • #2: How many folks have looked for code on djangosnippets? How many folks have cursed loudly, because djangosnippets doesn’t have a search field? How many folks have read the FAQ where James Bennett complains that Django doesn’t have a leading candidate for search, which is why djangosnippets has no search capability? How many people think that’s a lame excuse? If full-text indexing is beyond scope, here’s a reasonable solution, implementable entirely within Django.