Skip to content

Commit 854e333

Browse files
authored
Merge pull request #121 from UCL-ARC/development
updating production: sorting films ignoring "the" and "a"
2 parents 9c4541a + 8855008 commit 854e333

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

mod_app/models/film_model.py

+31
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from ckeditor_uploader.fields import RichTextUploadingField
22
from django.db import models
3+
from django.db.models import Case, When, CharField
4+
from django.db.models.functions import Substr, Lower, Trim
35
from django.core.exceptions import ValidationError
46
from django.urls import reverse
57

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

1719

20+
class FilmManager(models.Manager):
21+
def get_queryset(self):
22+
"""Order films first by number, then alphabetically, discarding prefix if they start with 'The' or 'A'"""
23+
return (
24+
super()
25+
.get_queryset()
26+
.annotate(
27+
# annotate a field for sorting the title, ignoring "A " or "The "
28+
sort_title=Case(
29+
# starts with "The"
30+
When(
31+
title__iregex=r"^The\s+",
32+
then=Lower(Trim(Substr("title", 5))),
33+
),
34+
# starts with "A"
35+
When(
36+
title__iregex=r"^A\s+",
37+
then=Lower(Trim(Substr("title", 3))),
38+
),
39+
# then other titles
40+
default=Lower(Trim("title")),
41+
output_field=CharField(),
42+
),
43+
)
44+
.order_by("sort_title")
45+
)
46+
47+
1848
class Film(models.Model):
1949
def __str__(self):
2050
return f"{self.title}"
2151

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

55+
objects = FilmManager()
2556
title = models.CharField(max_length=100)
2657
alt_titles = models.TextField(
2758
blank=True,

0 commit comments

Comments
 (0)