To illustrate the query expressions, let's create the viral video detail view and plug it into the URL configuration, as follows:
- Create the viral_video_detail view in views.py, as follows:
# viral_videos/views.py import datetime, logging
from django.conf import settings
from django.db import models
from django.shortcuts import render, get_object_or_404
from .models import ViralVideo
POPULAR_FROM = getattr(
settings, "VIRAL_VIDEOS_POPULAR_FROM", 500
)
logger = logging.getLogger(__name__)
def viral_video_detail(request, pk):
yesterday = datetime.date.today() - datetime.timedelta(days=1)
qs = ViralVideo.objects.annotate(
total_views=models.F("authenticated_views") +
models.F("anonymous_views"),
label=models.Case(
models.When(total_views__gt=POPULAR_FROM,
then=models.Value("popular")),
models.When(created__gt=yesterday,
then=models.Value("new")),
default=models.Value("cool"),
output_field=models.CharField()))
# DEBUG: check the SQL query that Django ORM generates
logger.debug(qs.query)
qs = qs.filter(pk=pk)
if request.user.is_authenticated:
qs.update(authenticated_views=models.F(
"authenticated_views") + 1)
else:
qs.update(anonymous_views=models.F(
"anonymous_views") + 1)
video = get_object_or_404(qs)
return render(request,
"viral_videos/viral_video_detail.html",
{'video': video})
- Define the URL configuration for the app, shown as follows:
# viral_videos/urls.py from django.urls import path
from .views import viral_video_detail
urlpatterns = [
path('<int:pk>/', viral_video_detail,
name='viral-video-detail'),
]
- Include the URL configuration of the app in the project's root URL configuration,
as follows:
# project/urls.py
from django.urls import include, path urlpatterns = [ # ...
path('videos/', include('viral_videos.urls')), ]
- Create a template for the viral_video_detail view, as follows:
{# templates/viral_videos/viral_video_detail.html #} {% extends "base.html" %}
{% load i18n %}
{% block content %}
<h1>{{ video.title }}
<span class="badge">{{ video.label }}</span>
</h1>
<div>{{ video.embed_code|safe }}</div>
<div>
<h2>{% trans "Impressions" %}</h2>
<ul>
<li>{% trans "Authenticated views" %}:
{{ video.authenticated_views }}</li>
<li>{% trans "Anonymous views" %}:
{{ video.anonymous_views }}</li>
<li>{% trans "Total views" %}:
{{ video.total_views }}</li>
</ul>
</div>
{% endblock %}
- Set up administration for the viral_videos app, as follows, and add some videos to the database when you are finished:
# viral_videos/admin.py
from django.contrib import admin
from .models import ViralVideo
admin.site.register(ViralVideo)