Skip to content

Commit

Permalink
adding film manager to sort titles by number then alphabetically, ign…
Browse files Browse the repository at this point in the history
…oring the and a
  • Loading branch information
acholyn committed Sep 24, 2024
1 parent 0d6ebad commit 92d3084
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions mod_app/models/film_model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from ckeditor_uploader.fields import RichTextUploadingField
from django.db import models
from django.db.models import Case, When, Value, CharField
from django.db.models.functions import Substr, Lower, Trim
from django.core.exceptions import ValidationError
from django.urls import reverse

Expand All @@ -15,13 +17,48 @@ def validate_format_other(value, format_type):
raise ValidationError("Please provide format details; you've selected 'other' ")


class FilmManager(models.Manager):
def get_queryset(self):
"""Order films first by number, then alphabetically, discarding prefix if they start with 'The' or 'A'"""
return (
super()
.get_queryset()
.annotate(
# new field 'is_number' to check if the title starts with a number
is_number=Case(
When(title__regex=r"^\d", then=Value(0)),
default=Value(1),
output_field=models.IntegerField(),
),
# annotate a field for sorting the title, ignoring "A " or "The "
sort_title=Case(
# starts with "The"
When(
title__iregex=r"^The\s+",
then=Lower(Trim(Substr("title", 5))),
),
# starts with "A"
When(
title__iregex=r"^A\s+",
then=Lower(Trim(Substr("title", 3))),
),
# then other titles
default=Lower(Trim("title")),
output_field=CharField(),
),
)
.order_by("is_number", "sort_title")
)


class Film(models.Model):
def __str__(self):
return f"{self.title}"

def get_absolute_url(self):
return reverse("film_detail", kwargs={"pk": self.pk})

objects = FilmManager()
title = models.CharField(max_length=100)
alt_titles = models.TextField(
blank=True,
Expand Down

0 comments on commit 92d3084

Please sign in to comment.