Example #1
0
def get_top_rated(request, *args, **kwargs):
    """ Returns QuerySet of all material sorted by view count
    """
    per_page = settings.REST_FRAMEWORK['PAGINATE_BY']
    sql = """
        SELECT m.id, m.material_id, m.title, m.version, m.categories,
               m.material_type, m.modified, avg(mr.rate) as avg_rate, count(mr.rate) AS rate_count
        FROM vpr_content_material AS m
        INNER JOIN vpr_content_materialrating AS mr
        ON m.id = mr.material_id
        GROUP BY mr.material_id
        ORDER BY avg_rate DESC, rate_count DESC
        LIMIT %d;
        """ % per_page
    cur = connection.cursor()
    res = cur.execute(sql)

    materials = []
    for m in cur:

        # getting categories
        cids = models.restoreAssignedCategory(m[4])
        categories = []
        for ci in range(len(cids)):
            categories.append((cids[ci], models.getCategoryName(cids[ci]))) 

        # getting authors
        pids = models.getMaterialPersons(m[0])['author'].split(',')
        pnames = models.getPersonName(pids)
        if not isinstance(pnames, list):
            pnames = [pnames,] 
        authors = []
        for pi in range(len(pids)):
            authors.append((pids[pi], pnames[pi])) 

        s_material = {
            'material_id': m[1],
            'version': m[3],
            'material_type': m[5],
            'title': m[2],
            'categories': categories, 
            'rating': m[7],
            'rating_count': m[8],
            'author': authors,
            'modified': m[6],
            }
        materials.append(s_material)

    return Response(materials)
Example #2
0
def queryMaterialByViewCount(request, *args, **kwargs):
    """ Returns QuerySet of all material sorted by view count
    """
    #per_page = settings.REST_FRAMEWORK['PAGINATE_BY']
    per_page = 50
    sql = """SELECT m.id, m.material_id, m.version, m.material_type, 
                    m.title, m.categories, m.description, m.modified,
                    mv.count
             FROM vpr_content_material as m
             INNER JOIN vpr_content_materialviewcount as mv
             ON (m.id=mv.material_id) 
             ORDER BY mv.count DESC LIMIT %d; 
             """ % (per_page)
    materials = []
    for m in models.Material.objects.raw(sql):

        # getting categories
        cids = models.restoreAssignedCategory(m.categories)
        categories = []
        for ci in range(len(cids)):
            categories.append((cids[ci], models.getCategoryName(cids[ci]))) 

        # getting authors
        pids = models.getMaterialPersons(m.id)['author'].split(',')
        pnames = models.getPersonName(pids)
        if not isinstance(pnames, list):
            pnames = [pnames,] 
        authors = []
        for pi in range(len(pids)):
            authors.append((pids[pi], pnames[pi])) 

        s_material = {
            'material_id': m.material_id,
            'version': m.version,
            'material_type': m.material_type,
            'title': m.title,
            'categories': categories, 
            'count': m.count,
            'author': authors,
            'modified': m.modified,
            }
        materials.append(s_material)

    return Response(materials)
Example #3
0
    def list(self, request, *args, **kwargs):
        """ Customized function for listing materials with same ID
        """
        # in case of listing all version of specific material
        material_id = kwargs.get('mid', None)

        # caching
        query_st = request.GET.urlencode() or material_id or 'all'
        cache_key = 'list-materials:' + query_st
        result = cache.get(cache_key)

        if result:
            sr_data = eval(result)
        else:
            try: 
                # show all versions of specific material
                if material_id: 
                    self.object_list = self.model.objects.filter(
                        material_id=material_id
                        )
                else:
                    # get the or criterias
                    or_crits = getOrFields(request)

                    self.object_list = self.model.objects
                    # filter by person roles
                    mp_objs = models.MaterialPerson.objects
                    mp_list = []
                    role_in_query = False
                    for role in settings.VPR_MATERIAL_ROLES:
                        role_id = settings.VPR_MATERIAL_ROLES.index(role)
                        if request.GET.get(role, ''):
                            query = request.GET.get(role, '').split(',')
                            query = [int(pid) for pid in query]
                            mp_list.extend(mp_objs.filter(role=role_id, person_id__in=query))
                            role_in_query = True
                    allow_materials = []
                    for mp in mp_list:
                        if mp.material_rid not in allow_materials:
                            allow_materials.append(int(mp.material_rid))

                    # do the filtering
                    browse_on = {}
                    fields = [item for item in request.GET if item in self.br_fields]
                    [browse_on.update({item:request.GET[item]}) for item in fields]
                    if role_in_query:
                        browse_on['pk__in'] = allow_materials
                    self.object_list = self.object_list.filter(**browse_on)

                    # custom fileting with categories 
                    self.object_list = queryCategory(
                        request,
                        self.object_list,
                        'categories' in or_crits
                        )

                    # continue with sorting
                    sort_fields = request.GET.get('sort_on', '')
                    if sort_fields:
                        #import pdb;pdb.set_trace()
                        self.object_list = self.object_list.order_by(sort_fields)
            except:
                raise404(request) 

            # Default is to allow empty querysets.  This can be altered by setting
            # `.allow_empty = False`, to raise 404 errors on empty querysets.
            allow_empty = self.get_allow_empty()
            if not allow_empty and len(self.object_list) == 0:
                error_args = {'class_name': self.__class__.__name__}
                raise404(request, self.empty_error % error_args)

            # Pagination size is set by the `.paginate_by` attribute,
            # which may be `None` to disable pagination.
            page_size = self.get_paginate_by(self.object_list)
            if page_size:
                packed = self.paginate_queryset(self.object_list, page_size)
                paginator, page, queryset, is_paginated = packed
                serializer = self.get_pagination_serializer(page)
            else:
                serializer = self.get_serializer(self.object_list)

            # silly steps: remove heavy data from response
            try:
                for res in range(len(serializer.data['results'])):
                    material = serializer.data['results'][res]
                    material['text'] = ''
                    if request.GET.get('names', None):
                        # add the category names
                        cats = []
                        for mc in material['categories']:
                            cats.append([mc, models.getCategoryName(mc)])
                        material['categories'] = cats
                        # .. and the person names
                        for role in settings.VPR_MATERIAL_ROLES:
                            if material.has_key(role):
                                persons = []
                                pids = [int(pid) for pid in material[role].split(',')]
                                for pc in pids:
                                    persons.append([pid, models.getPersonName(pid)])
                                material[role] = persons
                    serializer.data['results'][res] = material

            except:
                # should we shout anything?
                pass

            # setting cache
            sr_data = serializer.data
            for mi in sr_data['results']:
                mi['modified'] = str(mi['modified'])
            cache.set(cache_key, str(sr_data), CACHE_TIMEOUT_MATERIAL)

        return Response(sr_data)