【问题标题】:Using filter and order_by in a query在查询中使用 filter 和 order_by
【发布时间】:2015-03-18 05:40:29
【问题描述】:

我想创建一个简单的博客,在按类别过滤的索引页面中显示 5 个新帖子。我阅读了另一个关于此的问题,但是当我尝试时它根本不起作用

list_blog_canada = Blog.objects.filter(category_id=1).order_by('publish')

我想知道这没有任何问题,问题出在我的模型上吗?什么的

models.py

class Category(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

    def __str__(self):
        return self.title

class Blog(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)
    content = models.TextField()
    publish = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Category)

index.html

{% if listblogca %}
                        {% for entry in listblogca|slice:':5' %}
                            <ul><li><a href="/baiviet/{{ entry.slug }}/">{{ entry.title|truncatechars:25 }}</a></li></ul>
                        {% endfor %}
                        {% else %}
                            <h4>THERE ARE NO POSTS</h4>
                {% endif %}

感谢您的阅读。我希望我能尽快得到你的帮助

【问题讨论】:

  • 什么不起作用?你的listblogca 是空的?你有什么错误?
  • @catavaran 它显示列表,但我希望它按新闻排序到较旧

标签: django django-views


【解决方案1】:

如果您想获取最新的帖子,则需要在order_by 方法中的字段名称中添加- 符号:

list_blog_canada = Blog.objects.filter(category__id=1).order_by('-publish')

升序/降序的文档是here

【讨论】:

【解决方案2】:

好像 Blog 对象没有 category_id 字段。

这里是一些用于查询的文档 https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

【讨论】:

  • 如果您尝试根据外键进行过滤,请使用类似blogs.objects.filter(category__id=1) *注意有两个下划线 *
  • 这个问题谈到了类似stackoverflow.com/questions/1981524/…
  • 您好!感谢您的回复。但是 Django 可以理解 category_id 是什么。我以前用过:)
猜你喜欢
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2017-05-08
相关资源
最近更新 更多