Django入门与实践-第20章:QuerySets(查询结果集)(完结)

http://127.0.0.1:8000/boards/1/
#boards/models.py
from django.utils.text import Truncator
class Topic(models.Model):
    # ...
    def __str__(self):
        return self.subject
class Post(models.Model):
    # ...
    def __str__(self):
        truncated_message = Truncator(self.message)
        return truncated_message.chars(30)

python manage.py shell
from boards.models import Board
# First get a board instance from the database
board = Board.objects.get(name=‘Django‘)
board.topics.all()
board.topics.count()
#现在统计一个版块下面的回复数量有点麻烦,因为回复并没有和 Board 直接关联
from boards.models import Post
Post.objects.all()
Post.objects.count()
这里一共11个回复,但是它并不全部属于 "Django" 这个版块的。我们可以这样来过滤
from boards.models import Board, Post
board = Board.objects.get(name=‘Django‘)
Post.objects.filter(topic__board=board)
Post.objects.filter(topic__board=board).count()
最后一个任务是标识版块下面的最后一条回复
Post.objects.filter(topic__board=board).order_by(‘-created_at‘)
Post.objects.filter(topic__board=board).order_by(‘-created_at‘).first()

#boards/models.py
class Board(models.Model):
    def get_posts_count(self):
        return Post.objects.filter(topic__board=self).count()
    def get_last_post(self):
        return Post.objects.filter(topic__board=self).order_by(‘-created_at‘).first()

<--templates/home.html-->
<!--以下代码应该在<small></small>中但是未通过-->
<a href="{% url ‘topic_posts‘ board.pk post.topic.pk %}">
   By {{ post.created_by.username }} at {{ post.created_at }}
</a>

{% extends ‘base.html‘ %}
{% block breadcrumb %}
    <li class="breadcrumb-item active">Boards</li>
{% endblock %}

{% block content %}
    <table class="table">
        <thead class="thead-inverse">
            <tr>
                <th>Board</th>
                <th>Posts</th>
                <th>Topics</th>
                <th>Last Post</th>
            </tr>
        </thead>
        <tbody>
        {% for board in boards %}
        <tr>
            <td>
            <a href="{% url ‘board_topics‘ board.pk %}">{{ board.name }}</a>
            <small class="text-muted d-block">{{ board.description }}</small>
            </td>
            <td class="align-middle">{{ board.get_posts_count }}</td>

            <td class="align-middle">{{ board.topics.count }}</td>
             <td class="align-middle">
                {% with post=board.get_last_post %}
                    <small>
                    </small>
                {% endwith %}
            </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}
<!--看起来好像有问题,如果没有回复的时候程序会崩溃-->
<!--templates/home.html-->
{% with post=board.get_last_post %}
    {% if post %}
        <small>
            <a href="{% url ‘topic_posts‘ board.pk post.topic.pk %}">
                By {{ post.created_by.username }} at {{ post.created_at }}
            </a>
        </small>
    {% else %}
        <small class="text-muted">
            <em>No posts yet.</em>
        </small>
    {% endif %}
{% endwith %}
python manage.py shell
from django.db.models import Count
from boards.models import Board
board = Board.objects.get(name=‘Django‘)
topics = board.topics.order_by(‘-last_updated‘).annotate(replies=Count(‘posts‘))
for topic in topics:
    print(topic.replies)

#我们来做一个小小的修复,因为回复里面不应该包括发起者的帖子
topics = board.topics.order_by(‘-last_updated‘).annotate(replies=Count(‘posts‘) - 1)
for topic in topics:
    print(topic.replies)
#boards/views.py 更新
from django.db.models import Count
def board_topics(request, pk):
    board = get_object_or_404(Board, pk=pk)
    topics = board.topics.order_by(‘-last_updated‘).annotate(replies=Count(‘posts‘) - 1)
    return render(request, ‘topics.html‘, {‘board‘: board, ‘topics‘: topics})

<!--templates/topics.html-->
{% for topic in topics %}
    <tr>
        <td><a href="{% url ‘topic_posts‘ board.pk topic.pk %}">{{ topic.subject }}</a></td>
        <td>{{ topic.starter.username }}</td>
        <td>{{ topic.replies }}</td>
        <td>0</td>
        <td>{{ topic.last_updated }}</td>
    </tr>
{% endfor %}

原文地址:https://www.cnblogs.com/larken/p/9565121.html

时间: 2024-08-30 00:34:14

Django入门与实践-第20章:QuerySets(查询结果集)(完结)的相关文章

Django入门与实践-第12章:复用模板(完结)

http://127.0.0.1:8000/http://127.0.0.1:8000/boards/1/http://127.0.0.1:8000/boards/2/http://127.0.0.1:8000/boards/3/ <!--static/css/app.css--> .navbar-brand { font-family: 'Peralta', cursive; } <!--templates/base.html--> {% load static %}<!D

Django入门与实践-第19章:主题回复(完结)

http://127.0.0.1:8000/boards/1/topics/1/reply/ http://127.0.0.1:8000/boards/1/topics/1/ #myproject/urls.py url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/reply/$',views.reply_topic, name='reply_topic'), #boards/forms.py from .models import

Django入门与实践-第21章:迁移(完结)

http://127.0.0.1:8000/boards/1/ python manage.py migrate #boards/models.py class Topic(models.Model): views = models.PositiveIntegerField(default=0) # <- here python manage.py makemigrations python manage.py migrate #boards/views.py def topic_posts(r

Django入门与实践 17-26章总结

Django入门与实践-第17章:保护视图 Django 有一个内置的视图装饰器 来避免它被未登录的用户访问: 现在如果用户没有登录,将被重定向到登录页面: 现在尝试登录,登录成功后,应用程序会跳转到原来所在的位置. Django入门与实践-第18章:访问已登录用户 现在我么可以改进 new_topic 视图,将发布主题的用户设置当前登录的用户,取代之前直接从数据库查询出来的第一个用户, 之前这份代码是临时的,因为那时候还没有方法去获取登录用户,但是现在可以了: 有两个关键字参数,pk用于唯一标

敏捷软件开发:原则、模式与实践——第20章 咖啡的启示

第20章 咖啡的启示 这个例子对于教学有很多好处.它短小.易于理解并且展示了如何应用面向对象设计原则去管理依赖和分类关注点.但从另一方面来说,它的短小也意味着这种分离带来的好处可能抵不过其成本.就当做一个设计思路来看吧. 20.1 Mark IV型专用咖啡机20.1.1 规格说明书 Mark IV型专用咖啡机一次可以产出12杯咖啡.使用者把过滤器放置在支架上,在其中装入研磨好的咖啡,然后把支架推入其容器中.接着,使用者向滤水器中倒入12杯水并按下冲煮(Brew)按钮.水一直加热到沸腾.不断产生的

python编程:从入门到实践----第四章&gt;操作列表

一.遍历整个列表 1-1.假设有一个魔术师名单,需要将其中每个魔术师的名字都打印出来. # 用for循环来打印魔术师名单中的名字 magicians=['alice','david','carolina'] for magician in magicians: #这里面的magician和magicians是便于让读者得知for循环在哪个列表中进行遍历 print(magician) #输出结果: alice david carolina 解析以上代码: a. 先定义一个列表 b. 定义一个fo

Django入门与实践 1-16章总结

注意事项:随时备份.随时记录.从宏观到微观 不闻不若闻之,闻之不若见之,见之不若知之,知之不若行之:学至于行之止矣 安装 Python 3.6.2 pip install django==1.11.4 django-admin startproject myproject python manage.py runserver http://127.0.0.1:8000 使用组合键 Control + C 来终止开发服务器. django-admin startapp boards setting

《Python编程从入门到实践》第二章_变量和简单数据类型

什么是变量呢? 举例: >>> message = "Hello,Python!" >>> print (message) Hello,Python! 这里的message就是变量.在程序中可随时修改变量的值,而python将始终记录变量的最新值. 变量命令的规则有哪些呢? 变量只能包含字母数字下划线. 变量名不能包含空格,但可以使用下划线来分割其中的单词 不要将python关键字和函数名作为变量名 变量名应既简单又具有描述性 慎用小写字符l和大写字

py从入门到实践 第四章

4.1 遍立列表 ~= shell 数组————————————————————————————————————————————thrink = ['link','path','pwd']for i in thrink: print(i)————————————————————————————print缩进 = 4个空格循环后不必要的缩进magicians = [ 'alice','david', 'carolina'] for magician in magicians: print(magi