Skip to content

Instantly share code, notes, and snippets.

@SalahAdDin
Last active Mar 10, 2018
Embed
What would you like to do?
Recipe views
# Golbal queries
class GlobalQueryMixin(object):
"""
Mixin for get a global template query
post: Most ranked recipe
tops: Five most ranked recipes
top fruits: Three most ranked fruit recipes
random: Four random recipes
fruits: Four fruit recipes
desserts: Four desserts recipes
salads: Four salad recipes
pizza: Four pizza recipes
"""
main = Recipe.objects.filter(shared=True)
def get_context_data(self, **kwargs):
categories = Category.objects.filter(slug__in=['fruits', 'desserts', 'salads', 'pizza'])
context = super(GlobalQueryMixin, self).get_context_data(**kwargs)
context['post'] = self.main.order_by('rating_score').first()
context['tops'] = self.main.order_by('rating_score')[:5]
context['top_fruits'] = self.main.order_by('rating_score').filter(category__slug='fruits')[:4]
context['random'] = self.main.order_by('?')[:4]
context['categories'] = categories
return context
class PopRecipeListView(GlobalQueryMixin, ListView):
model = Recipe
context_object_name = "recipe_list"
template_name = 'recipe/recipe_top_list.html'
def dispatch(self, request, *args, **kwargs):
api_key = settings.DISQUS_API_KEY
forum = settings.DISQUS_WEBSITE_SHORTNAME
url = 'https://disqus.com/api/3.0/forums/listThreads.json?api_key={0}&forum={1}&limit=100'.format(
api_key,
forum
)
raw = requests.get(url)
dict = json.loads(raw.content)
self.values = {}
for thread in dict['response']:
item = {thread['slug']: thread['posts']}
self.values.update(item)
return super(PopRecipeListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PopRecipeListView, self).get_context_data(**kwargs)
# Add in a QuerySet of all the books
# context['feed'] = "/feed/popular/"
context['top_title'] = _('Popular Recipes')
context['top_message'] = _('popular posts by comments')
context['pop'] = True
return context
def get_comments_number(self, recipe_slug):
return self.values[recipe_slug]
def get_queryset(self):
qs = super(PopRecipeListView, self).get_queryset()
if qs:
qs = qs.extra(
select={
'comments': '{0}'.format(
self.get_comments_number(Recipe.slug)
)
}
).filter(shared=True).order_by('-comments')
return qs
@SalahAdDin
Copy link
Author

SalahAdDin commented Mar 9, 2018

Alternative:

qs = qs.annotate(num_comments=self.get_comments_number(F('slug'))).filter(shared=True).order_by('-num_comments')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment