1. 간단한 구현
관련 파일:
from django.conf.urls import url from . import views urlpatterns = [ url(r'^index.html/$',views.index), url(r'^article/(?P<article_type>\d+)-(?P<category>\d+).html/$',views.article) ] url.py
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> </head> <body> <h2>过滤条件</h2> <div> {% if kwargs.article_type == 0 %} <a href="/article/0-{{ kwargs.category }}.html">全部</a> {% else %} <a href="/article/0-{{ kwargs.category }}.html">全部</a> {% endif %} {% for row in article_type %} {% if row.id == kwargs.article_type %} <a href="/article/{{ row.id }}-{{ kwargs.category }}.html">{{ row.caption }}</a> {% else %} <a href="/article/{{ row.id }}-{{ kwargs.category }}.html">{{ row.caption }}</a> {% endif %} {% endfor %} </div> <div> {% if kwargs.category == 0 %} <a href="/article/{{ kwargs.article_type }}-0.html">全部</a> {% else %} <a href="/article/{{ kwargs.article_type }}-0.html">全部</a> {% endif %} {% for row in category %} {% if row.id == kwargs.category %} <a href="/article/{{ kwargs.article_type }}-{{ row.id }}.html">{{ row.caption }}</a> {% else %} <a href="/article/{{ kwargs.article_type }}-{{ row.id }}.html">{{ row.caption }}</a> {% endif %} {% endfor %} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body> </html> article.html
데이터베이스 구조:
from django.db import models # Create your models here. class Categoery(models.Model): caption = models.CharField(max_length=16) class ArticleType(models.Model): caption = models.CharField(max_length=16) class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=255) category = models.ForeignKey(Categoery) article_type = models.ForeignKey(ArticleType)
처리 파일:
from . import models def article(request,*args,**kwargs): search_dict = {} for key,value in kwargs.items(): kwargs[key] = int(value) # 把字符类型转化为int类型 方便前端做if a == b 这样的比较 if value !='0': search_dict[key] = value articles = models.Article.objects.filter(**search_dict) # 字典为空时表示搜索所有 article_type = models.ArticleType.objects.all() category = models.Categoery.objects.all() return render(request,'article.html',{'articles':articles, 'article_type':article_type, 'category':category , 'kwargs':kwargs})
참고: 필요하지 않습니다. 이 기능을 구현하기 어렵습니다. 가장 중요한 것은 내부 아이디어를 명확히 하는 것입니다. 먼저 URL 액세스 경로 형식인 http://127.0.0.1:8000/article/0-0.html을 결정합니다. 처음 0은 article_type 필드를 나타냅니다. 두 번째 0은 카테고리 필드를 나타냅니다. 0이면 이 필드의 모든 정보를 검색한다는 의미입니다. 이를 확인하는 것이 처리 파일에 대한 검색 처리가 있음을 확인하는 것입니다. 관련 검색어에 대한 사전 search_dict 0이면 세 번째 핵심 사항을 모두 검색하는 것도 매우 영리한 방법이며, kwargs 매개변수를 다시 프런트 엔드에 전달하는 것은 천재적인 일입니다.
2. 또 다른 시도(로딩 메모리 조정)
ArticleType 유형은 블로그에 대한 고정 데이터이므로 향후 로드할 수 없습니다. 쿼리 속도를 높이기 위해 데이터를 메모리에 저장
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> </head> <body> <h2>过滤条件</h2> <div> {% if kwargs.article_type_id == 0 %} <a href="/article/0-{{ kwargs.category_id }}.html">全部</a> {% else %} <a href="/article/0-{{ kwargs.category_id }}.html">全部</a> {% endif %} {% for row in article_type%} {% if row.0 == kwargs.article_type_id %} <a href="/article/{{ row.0 }}-{{ kwargs.category_id }}.html">{{ row.1 }}</a> {% else %} <a href="/article/{{ row.0 }}-{{ kwargs.category_id }}.html">{{ row.1 }}</a> {% endif %} {% endfor %} </div> <div> {% if kwargs.category_id == 0 %} <a href="/article/{{ kwargs.article_type_id }}-0.html">全部</a> {% else %} <a href="/article/{{ kwargs.article_type_id }}-0.html">全部</a> {% endif %} {% for row in category %} {% if row.id == kwargs.category_id %} <a href="/article/{{ kwargs.article_type_id }}-{{ row.id }}.html">{{ row.caption }}</a> {% else %} <a href="/article/{{ kwargs.article_type_id }}-{{ row.id }}.html">{{ row.caption }}</a> {% endif %} {% endfor %} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body> </html> article.html
from django.shortcuts import render from django.shortcuts import HttpResponse # Create your views here. def index(request): return HttpResponse('Ok') from . import models def article(request,*args,**kwargs): search_dict = {} for key,value in kwargs.items(): kwargs[key] = int(value) # 把字符类型转化为int类型 方便前端做if a == b 这样的比较 if value !='0': search_dict[key] = value print(kwargs) articles = models.Article.objects.filter(**search_dict) # 字典为空时表示搜索所有 article_type = models.Article.type_choice print(article_type) category = models.Categoery.objects.all() return render(request,'article.html',{'articles':articles, 'article_type':article_type, 'category':category , 'kwargs':kwargs}) 处理文件.py
데이터베이스 파일:
from django.db import models # Create your models here. class Categoery(models.Model): caption = models.CharField(max_length=16) # class ArticleType(models.Model): # caption = models.CharField(max_length=16) class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=255) category = models.ForeignKey(Categoery) # article_type = models.ForeignKey(ArticleType) type_choice = [ (1,'Python'), (2,'Linux'), (3,'大数据'), (4,'架构'), ] article_type_id = models.IntegerField(choices=type_choice)
3. simple_tag를 사용하여 코드 최적화
관련 파일:
from django.db import models # Create your models here. class Categoery(models.Model): caption = models.CharField(max_length=16) class ArticleType(models.Model): caption = models.CharField(max_length=16) class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=255) category = models.ForeignKey(Categoery) article_type = models.ForeignKey(ArticleType) # type_choice = [ # (1,'Python'), # (2,'Linux'), # (3,'大数据'), # (4,'架构'), # ] # article_type_id = models.IntegerField(choices=type_choice) 数据库文件.py
from django.shortcuts import render from django.shortcuts import HttpResponse # Create your views here. def index(request): return HttpResponse('Ok') from . import models def article(request, *args, **kwargs): search_dict = {} for key, value in kwargs.items(): kwargs[key] = int(value) # 把字符类型转化为int类型 方便前端做if a == b 这样的比较 if value != '0': search_dict[key] = value articles = models.Article.objects.filter(**search_dict) # 字典为空时表示搜索所有 article_type = models.ArticleType.objects.all() print(article_type) category = models.Categoery.objects.all() return render(request, 'article.html', {'articles': articles, 'article_type': article_type, 'category': category, 'kwargs': kwargs}) 处理文件.py
{% load filter %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style> .condition a{ display:inline-block; padding: 3px 5px; border: 1px solid black; } .condition a.active{ background-color: brown; } </style> </head> <body> <h2>过滤条件</h2> <div> {% filter_all kwargs 'article_type'%} {% filter_single article_type kwargs 'article_type'%} </div> <div> {% filter_all kwargs 'category'%} {% filter_single category kwargs 'category'%} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body> </html> article.html
templatetags 디렉토리를 생성하고, 디렉토리에 filter.py 파일을 생성합니다:
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def filter_all(kwargs,type_str): print(type_str) if type_str == 'article_type': if kwargs['article_type'] == 0: tmp = '<a href = "/article/0-%s.html" class ="active" > 全部 </a>'%(kwargs['category']) else: tmp = '<a href = "/article/0-%s.html"> 全部 </a>'%(kwargs['category']) elif type_str == 'category': if kwargs['category'] == 0: tmp = '<a href = "/article/%s-0.html" class ="active" > 全部 </a>' % (kwargs['article_type']) else: tmp = '<a href = "/article/%s-0.html"> 全部 </a>' % (kwargs['article_type']) return mark_safe(tmp) @register.simple_tag() def filter_single(type_obj,kwargs,type_str): print(type_str) tmp = '' if type_str == 'article_type': for row in type_obj: if row.id == kwargs['article_type']: tag = '<a class="active" href="/article/%s-%s.html">%s</a>\n'%(row.id,kwargs['category'],row.caption) else: tag = '<a href="/article/%s-%s.html">%s</a>\n' % (row.id, kwargs['category'],row.caption) tmp +=tag elif type_str == 'category': for row in type_obj: if row.id == kwargs['category']: tag = '<a class="active" href="/article/%s-%s.html">%s</a>\n' % (kwargs['article_type'],row.id, row.caption) else: tag = '<a href="/article/%s-%s.html">%s</a>\n' % (kwargs['article_type'], row.id, row.caption) tmp += tag return mark_safe(tmp)
HTML 파일 주요 내용:
{% load filter %} <body> <h2>过滤条件</h2> <div class="condition"> {% filter_all kwargs 'article_type'%} {% filter_single article_type kwargs 'article_type'%} </div> <div class="condition"> {% filter_all kwargs 'category'%} {% filter_single category kwargs 'category'%} </div> <h2>查询结果</h2> <ul> {% for row in articles %} <li>{{ row.id }}-{{ row.title }}------[{{ row.article_type.caption }}]-[{{ row.category.caption }}]</li> {% endfor %} </ul> </body>
JSONP
JSONP(JSON with Padding)는 " JSON의 "사용 모드"는 주류 브라우저의 도메인 간 데이터 액세스 문제를 해결하는 데 사용할 수 있습니다. 동일 출처 정책으로 인해 일반적으로 server1.example.com에 위치한 웹 페이지는 HTML