【问题标题】:Filter by model field, Django按模型字段过滤,Django
【发布时间】:2014-09-24 04:12:16
【问题描述】:

我有一个创建文章的模型,我希望它具有“国家”和“类别”的值。我希望能够按这些值进行过滤。因此,如果有人点击该国家/地区,它将返回该国家/地区的所有文章,并且可以按类别进一步过滤。

型号:

class Article(models.Model):
    """Represents a wiki article"""
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=50, unique=True)
    text = models.TextField()
    author = models.ForeignKey(User)
    is_published = models.BooleanField(default=False, verbose_name="Publish?")
    created_on = models.DateTimeField(auto_now_add=True)
    objects = models.Manager()
    published = PublishedArticlesManager()
    country = models.ChoiceField(max_length=100)
    category = models.CharField(max_length=100)

我想做的是使用这个网址:

url(r'^country/(?P<country\w+)' , 'wiki.views.country',
        name = 'wiki_country'),

其中国家来自用户点击链接,然后返回一个页面,其中包含与该国家/地区的文章相对应的文章

这是目前列出所有文章的模板sn-p

{% if object_list %}

    <h2 class="articlePageTitle">All Articles</h2>
    <h3>Filter by country</h3>
    <h3>Filter by category</h3>

    <ul>
        {% for article in object_list %}
        <li>
            <a href="{% url wiki_article_detail article.slug %}">{{ article.title }}</a>
        </li>
{% endfor %}
    </ul>

我想我可以在模板标签中添加一个过滤器,但我不确定在视图中做什么。

【问题讨论】:

    标签: django python-2.7 django-models


    【解决方案1】:

    "Article.objects.filter(country=country_name)" 将返回 country = country_name 的所有文章对象。

    【讨论】:

    • 添加你的views.country,这样就很容易理解实际的问题了。
    • 视图部分是我想要弄清楚的。我会努力的,谢谢以上。
    猜你喜欢
    • 2015-03-25
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多