django组合搜索(搜索标签存内存中)

models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models

# Create your models here.

class ArticleTag(models.Model):
    caption = models.CharField(max_length=12)
    def __unicode__(self):
        return self.caption


class Article(models.Model):
    title = models.CharField(max_length=32, unique=True)
    content = models.TextField()
    author = models.CharField(max_length=32)
    cate_types = (
        (1, 'smartArticle'),
        (2, 'urlArticle'),
        (3, 'farmArticle'),
        (4, 'cookerArticle'),
    )
    category = models.IntegerField(choices=cate_types)
    article_tag = models.ForeignKey(ArticleTag)
    def __unicode__(self):
        return self.title

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
#注意这里<...>中的命名
    url(r'^article-(?P\d+)-(?P\d+).html', views.article, name='article'),
]

views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from app01 import models
# Create your views here.


def article(request, *args, **kwargs):
    # print kwargs
    condition = {}
    for k, v in kwargs.items():
        kwargs[k] = int(v)
        if v == '0':
            pass
        else:
            condition[k] = v
    print condition
    articles = models.Article.objects.filter(**condition)
#注意存内存中的输出到模板这样。。
    cate_types_list = models.Article.cate_types
    article_tags = models.ArticleTag.objects.all()
    return render(request, 'article.html', {'articles': articles, 'article_tags': article_tags, 'cate_types': cate_types_list, 'kwargs': kwargs})

template-article.html




    
    
    



{% if kwargs.article_tag_id == 0 %} 全部 {% else %} 全部 {% endif %} {% for tag in article_tags %} {% if kwargs.article_tag_id == tag.id %} {{ tag }} {% else %} {{ tag }} {% endif %} {% endfor %}
{% if kwargs.category == 0 %} 全部 {% else %} 全部 {% endif %} {% for c in cate_types %} {% if kwargs.category == c.0 %} {{ c.1 }} {% else %} {{ c.1 }} {% endif %} {% endfor %} {% for article in articles %}

{{ article.title }}

{{ article.author }} ---{{ article.article_tag }} ---{{ article.get_category_display }}

{{ article.content }}

{% endfor %}

你可能感兴趣的:(django组合搜索(搜索标签存内存中))