Beispiel #1
0
 def test_annotation(self):
     annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'))
     self.assertEqual(annotated_qs.count(), 2)
     
     food_a, food_b = annotated_qs
     
     self.assertEqual(food_a.score, 4)
     self.assertEqual(food_a.name, 'apple')
     
     self.assertEqual(food_b.score, 3)
     self.assertEqual(food_b.name, 'orange')
     
     annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating'))
     self.assertEqual(annotated_qs.count(), 2)
     
     food_b, food_a = annotated_qs
     
     self.assertEqual(food_b.score, 15)
     self.assertEqual(food_b.name, 'orange')
     
     self.assertEqual(food_a.score, 12)
     self.assertEqual(food_a.name, 'apple')
     
     annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Avg('rating'))
     self.assertEqual(annotated_qs.count(), 2)
     
     food_b, food_a = annotated_qs
     
     self.assertEqual(food_b.score, 5)
     self.assertEqual(food_b.name, 'orange')
     
     self.assertEqual(food_a.score, 3)
     self.assertEqual(food_a.name, 'apple')
Beispiel #2
0
    def order_by_rating(self, aggregator=models.Sum, descending=True,
                        queryset=None, alias='score'):
        related_field = get_content_object_field(self.model)

        if queryset is None:
            queryset = self.rated_model._default_manager.all()

        ordering = descending and '-%s' % alias or alias

        if not is_gfk(related_field):
            query_name = related_field.related_query_name()

            if len(self.query.where.children):
                queryset = queryset.filter(**{
                    '%s__pk__in' % query_name: self.values_list('pk')
                })

            return queryset.annotate(**{
                alias: aggregator('%s__score' % query_name)
            }).order_by(ordering)

        else:
            return generic_annotate(
                queryset,
                self,
                aggregator('score'),
                related_field,
                alias=alias
            ).order_by(ordering)
    def order_by_rating(self,
                        aggregator=models.Sum,
                        descending=True,
                        queryset=None,
                        alias='score'):
        related_field = get_content_object_field(self.model)

        if queryset is None:
            queryset = self.rated_model._default_manager.all()

        if not is_gfk(related_field):
            ordering = descending and '-%s' % alias or alias
            query_name = related_field.related_query_name()

            if len(self.query.where.children):
                queryset = queryset.filter(
                    **{'%s__pk__in' % query_name: self.values_list('pk')})

            return queryset.annotate(
                **{
                    alias: aggregator('%s__score' % query_name)
                }).order_by(ordering)

        else:
            return generic_annotate(queryset, related_field,
                                    aggregator('score'), self, descending,
                                    alias)
Beispiel #4
0
 def with_hit_count(self):
     from .models import Chapter
     return generic_annotate(
         self,
         HitCount,
         Sum("volume__chapter__hitcount_object__hits"),
         alias="hit_count",
         force_rel_model=Chapter,
     )
Beispiel #5
0
 def with_hit_count(self):
     from .models import Chapter
     return generic_annotate(
         self,
         HitCount,
         Sum("volume__chapter__hitcount_object__hits"),
         alias="hit_count",
         force_rel_model=Chapter,
     )
Beispiel #6
0
    def test_subset_annotation(self):
        todays_ratings = Rating.objects.filter(created__gte=datetime.date.today())
        annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings)
        self.assertEqual(annotated_qs.count(), 2)
        
        food_a, food_b = annotated_qs

        self.assertEqual(food_a.score, 8)
        self.assertEqual(food_a.name, 'apple')
        
        self.assertEqual(food_b.score, 7)
        self.assertEqual(food_b.name, 'orange')
Beispiel #7
0
def sort_posts(request, feed=None, sort=None):
    if feed:
        try:
            feed = Category.objects.get(shortname=feed)
            if feed.shortname == 'all':
                template = 'index.html'
                posts_unsorted = Post.objects.exclude(status__status_code_id='6').all()
                if sort == 'recent':
                    recent_posts = posts_unsorted.order_by('-timestamp')
                elif sort == 'highest':
                    recent_posts = generic_annotate(posts_unsorted, Vote.objects.filter(object_id__in=posts_unsorted), Sum('vote')).order_by('-score')
                elif sort == 'lowest':
                    recent_posts = generic_annotate(posts_unsorted, Vote.objects.filter(object_id__in=posts_unsorted), Sum('vote')).order_by('score')
                elif sort == 'popularity':
                    recent_posts = sorted(posts_unsorted, key=lambda post: post.popularity, reverse=True)
            elif feed.is_special == 1:
                template = 'special.html'
                posts_unsorted = Post.objects.exclude(status__status_code_id='6').filter(category_id__exact=feed.id)
                if sort == 'recent':
                    recent_posts = posts_unsorted.order_by('-timestamp')
                elif sort == 'highest':
                    recent_posts = generic_annotate(posts_unsorted, Vote.objects.filter(object_id__in=posts_unsorted), Sum('vote')).order_by('-score')
                elif sort == 'lowest':
                    recent_posts = generic_annotate(posts_unsorted, Vote.objects.filter(object_id__in=posts_unsorted), Sum('vote')).order_by('score')
                elif sort == 'popularity':
                    recent_posts = sorted(posts_unsorted, key=lambda post: post.popularity, reverse=True)
            else:
                template = 'index.html'
                posts_unsorted = Post.objects.exclude(status__status_code_id='6').filter(category_id__exact=feed.id)
                if sort == 'recent':
                    recent_posts = posts_unsorted.order_by('-timestamp')
                elif sort == 'highest':
                    recent_posts = generic_annotate(posts_unsorted, Vote.objects.filter(object_id__in=posts_unsorted), Sum('vote')).order_by('-score')
                elif sort == 'lowest':
                    recent_posts = generic_annotate(posts_unsorted, Vote.objects.filter(object_id__in=posts_unsorted), Sum('vote')).order_by('score')
                elif sort == 'popularity':
                    recent_posts = sorted(posts_unsorted, key=lambda post: post.popularity, reverse=True)
            if request.is_ajax():
                module = 'modules/recent_posts.html'
                return HttpResponse(render_block_to_string(module, 'content', {'recent_posts': recent_posts, 'sort': sort},
                                                           RequestContext(request)))
            else:
                categories = Category.objects.filter(is_special=0)
                special_categories = Category.objects.filter(is_special=1, is_active=1)
                form = NewPost()  # An unbound form

                return render(request, template, {
                    'form': form,
                    'feed': feed,
                    'categories': categories,
                    'sort': sort,
                    'special_categories': special_categories,
                    'recent_posts': recent_posts,
                }, context_instance=RequestContext(request))

        except Category.DoesNotExist:
            raise Http404
    else:
        raise Http404
Beispiel #8
0
 def with_hit_count_last_week(self):
     from .models import Chapter
     from django.db import connections
     return generic_annotate(
         self,
         HitCount,
         Count("volume__chapter__hitcount_object__hit__created"),
         alias="hit_count_last_week",
         force_rel_model=Chapter,
         rel_slice_pos=-2,
     ).extra(where=[Hit._meta.db_table + ".created > %s"], 
             params=[connections[self.db].ops.value_to_db_datetime(
                         timezone.now() - timedelta(days=7)
                    )],
            )
Beispiel #9
0
 def with_hit_count_last_week(self):
     from .models import Chapter
     from django.db import connections
     return generic_annotate(
         self,
         HitCount,
         Count("volume__chapter__hitcount_object__hit__created"),
         alias="hit_count_last_week",
         force_rel_model=Chapter,
         rel_slice_pos=-2,
     ).extra(
         where=[Hit._meta.db_table + ".created > %s"],
         params=[
             connections[self.db].ops.value_to_db_datetime(timezone.now() -
                                                           timedelta(
                                                               days=7))
         ],
     )
Beispiel #10
0
 def test_charfield_pks(self):
     a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple)
     a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple)
     o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange)
     
     annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name'))
     self.assertEqual(annotated_qs.count(), 2)
     
     food_a, food_b = annotated_qs
     
     self.assertEqual(food_b.score, 1)
     self.assertEqual(food_b.name, 'orange')
     
     self.assertEqual(food_a.score, 2)
     self.assertEqual(food_a.name, 'apple')
 
     aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name'))
     self.assertEqual(aggregated, 3)
Beispiel #11
0
 def test_ascending_order(self):
     annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), desc=False, alias='count')
     food_a, food_b = annotated_qs
     
     self.assertEqual(food_b.count, 4)
     self.assertEqual(food_b.name, 'apple')
Beispiel #12
0
 def test_custom_alias(self):
     annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), alias='count')
     food_a, food_b = annotated_qs
     
     self.assertEqual(food_a.count, 4)
     self.assertEqual(food_a.name, 'apple')
Beispiel #13
0
 def sorted_by_votes(self):
     return generic_annotate(self, Vote.object, Sum('vote'))