1 from random
import choice
3 from django
.db
import IntegrityError
4 from django
.utils
.text
import slugify
6 from mygpo
.decorators
import query_if_required
7 from mygpo
.categories
.models
import Category
, CategoryEntry
12 def __init__(self
, total
=100, num_cat
=10, podcasts_per_cat
=10):
14 self
.num_cat
= num_cat
15 self
.podcasts_per_cat
= podcasts_per_cat
16 self
._categories
= None
19 def _needs_query(self
):
20 return self
._categories
is None
23 categories
= list(Category
.objects
.filter(num_entries__gt
=0)
24 .filter(tags__isnull
=False)
25 .order_by('-modified')[:self
.total
]
26 .prefetch_related('tags'))
27 self
._categories
= categories
[:self
.num_cat
]
28 self
._tagcloud
= sorted(categories
[self
.num_cat
:],
29 key
=lambda x
: x
.title
.lower())
37 def max_entries(self
):
38 return max([e
.num_entries
for e
in self
.tagcloud
] + [0])
41 def min_entries(self
):
42 return min([e
.num_entries
for e
in self
.tagcloud
] + [0])
47 return self
._categories
50 def update_category(podcast
):
51 all_tags
= list(t
.tag
for t
in podcast
.tags
.all())
56 random_tag
= choice(all_tags
).strip()
59 category
, created
= Category
.objects
.get_or_create(
60 tags__tag
=slugify(random_tag
),
66 except IntegrityError
as ie
:
67 # check if category with this title already exists
68 # the exception message should be like:
69 # IntegrityError: duplicate key value violates unique
70 # constraint "categories_category_title_key"
71 if 'categories_category_title_key' not in str(ie
):
74 category
= Category
.objects
.get(title
=random_tag
)
78 # update modified timestamp
81 # add podcast to the category as newest entry
82 entry
, created
= CategoryEntry
.objects
.get_or_create(
88 # update modified timestamp