Esempio n. 1
0
def search(query, filter_by=None):
    filter_by = filter_by if filter_by is not None else 'all'
    if filter_by == 'all' or filter_by == 'profs':
        profs = Professor.objects.annotate(
            full_name=Concat('first_name', V(' '), 'last_name')).filter(
                Q(full_name__icontains=query), verified=True)
    else:
        profs = Professor.objects.none()

    if filter_by == 'all' or filter_by == 'deps':
        deps = Department.objects.filter(Q(name__icontains=query),
                                         verified=True)
    else:
        deps = Department.objects.none()

    if filter_by == 'all' or filter_by == 'unis':
        unis = University.objects.filter(Q(name__icontains=query),
                                         verified=True)
    else:
        unis = University.objects.none()

    return list(profs) + list(deps) + list(unis)
Esempio n. 2
0
    def get_queryset(self):
        if not (self.request.user.is_authenticated and self.request.user.is_staff):
            raise Http404

        queryset = Provider.objects.all()

        if self.q:
            queryset = queryset.annotate(
                name_company=Concat(
                    F("name"), Value(" "), F("company")
                )
            )
            terms = self.q.split()

            query = reduce(
                operator.and_,
                (Q(name_company__icontains=term) for term in terms)
            )

            queryset = queryset.filter(query)

        return queryset
Esempio n. 3
0
def articles(request):
    article_page = 'articles.html'
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            year = form.cleaned_data['year']
            author = form.cleaned_data['author']
            keyword = form.cleaned_data['keyword']
            print(title, year, author, keyword)
            articles_title_list = article_entity.objects.filter(
                article_title__icontains=title)
            if year != "":
                articles_title_list = articles_title_list.filter(
                    article_year=year)
            if author != "":
                author_list = author_entity.objects.annotate(
                    name=Concat('first_name', V(' '), 'last_name')).filter(
                        name__icontains=author)
                articles_title_list = articles_title_list.filter(
                    authors__in=author_list).distinct()
            if keyword != "":
                keyword_list = key_entity.objects.filter(
                    keyword__icontains=keyword)
                articles_title_list = articles_title_list.filter(
                    keywords__in=keyword_list).distinct()
            # articles_title_list.union(articles_years_list)
            print(articles_title_list)
            context = {
                'articles_title_list': articles_title_list,
                'form': form
            }
            return render(request, article_page, context)
    elif request.method == 'GET':
        form = PostForm()
        articles_title_list = article_entity.objects.order_by('article_title')
        print(articles_title_list)
        context = {'articles_title_list': articles_title_list, 'form': form}
        return render(request, article_page, context)
Esempio n. 4
0
def _localized_update_descendant_url_paths(page, old_url_path, new_url_path, language=None):
    localized_url_path = 'url_path'
    if language:
        localized_url_path = build_localized_fieldname('url_path', language)

    if connection.vendor in ('mssql', 'microsoft'):
        cursor = connection.cursor()
        update_statement = """
            UPDATE wagtailcore_page
            SET {localized_url_path}= CONCAT(%s, (SUBSTRING({localized_url_path}, 0, %s)))
            WHERE path LIKE %s AND id <> %s
        """.format(localized_url_path=localized_url_path)
        cursor.execute(update_statement, [new_url_path, len(old_url_path) + 1, page.path + '%', page.id])
    else:
        (Page.objects
            .rewrite(False)
            .filter(path__startswith=page.path)
            .exclude(**{localized_url_path: None})  # url_path_xx may not be set yet
            .exclude(pk=page.pk)
            .update(**{localized_url_path: Concat(
                Value(new_url_path),
                Substr(localized_url_path, len(old_url_path) + 1))}))
Esempio n. 5
0
class PredatorFilterView(DietsAccessRequired, FilterView):
    template_name = "diets/predator_filter.html"
    filterset_class = filters.PredatorFilter
    queryset = models.Predator.objects.annotate(
        search_term=Concat('species__common_name_eng',
                           'species__common_name_fre',
                           'species__scientific_name',
                           'species__id',
                           output_field=TextField()))

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["my_object"] = models.Predator.objects.first()
        context["field_list"] = [
            'season|Season',
            'id',
            'stomach_id',
            'species.common_name_eng',
            'cruise',
            'processing_date',
        ]
        return context
Esempio n. 6
0
def archive_log(request):
    """获取归档日志列表"""
    limit = int(request.GET.get('limit', 0))
    offset = int(request.GET.get('offset', 0))
    limit = offset + limit
    archive_id = request.GET.get('archive_id')

    archive_logs = ArchiveLog.objects.filter(archive=archive_id).annotate(
        info=Concat('cmd', V('\n'), 'statistics', output_field=TextField()))
    count = archive_logs.count()
    lists = archive_logs.order_by('-id')[offset:limit].values(
        'cmd', 'info', 'condition', 'mode', 'no_delete', 'select_cnt',
        'insert_cnt', 'delete_cnt', 'success', 'error_info', 'start_time',
        'end_time')
    # QuerySet 序列化
    rows = [row for row in lists]
    result = {"total": count, "rows": rows}
    # 返回查询结果
    return HttpResponse(json.dumps(result,
                                   cls=ExtendJSONEncoder,
                                   bigint_as_string=True),
                        content_type='application/json')
Esempio n. 7
0
 class Meta:
     # sort on the combination of these fields, since many are optional
     # NOTE: this causes problems for sorting related models in django admin
     # (i.e., sorting fragments by collection); see corpus admin for workaround
     ordering = [
         Concat(
             models.F("lib_abbrev"),
             models.F("abbrev"),
             models.F("name"),
             models.F("library"),
         )
     ]
     constraints = [
         # require at least one of library OR name
         models.CheckConstraint(
             check=(models.Q(library__regex=".+") | models.Q(name__regex=".+")),
             name="req_library_or_name",
         ),
         models.UniqueConstraint(
             fields=["library", "name"], name="unique_library_name"
         ),
     ]
Esempio n. 8
0
def getFolderUseMembers(memberId, keyword, cf_id):

    try:

        memberObj = member.objects.get(member_id=memberId)
        customerId = memberObj.customer_id_id

        folderUseMemberList = []
        nowUseMembers = contract_folder_member.objects.values_list(
            'member_id').filter(cf_id=cf_id, cfm_deleted=DELETE_FLG.USE)

        MemberList = member.objects.filter(
            customer_id=customerId, member_deleted=DELETE_FLG.USE).exclude(
                member_id__in=nowUseMembers).annotate(search_kj_name=Concat(
                    'member_kj_lastname', 'member_kj_firstname')).filter(
                        Q(search_kj_name__icontains=keyword)
                        | Q(member_email__icontains=keyword)).order_by(
                            'search_fg_name')

        for members in MemberList:
            folderUseMemberList.append({
                'last_name': members.member_kj_lastname,
                'first_name': members.member_kj_firstname,
                'member_id': members.member_id,
                'member_email': members.member_email
            })

    except Exception as ex:
        msg = "Exception.getFolderMembers(cf_id:" + str(cf_id) + ") ex:" + str(
            ex)
        print(msg)
        return {'result_code': -9999, 'msg': 'Exception : ' + str(ex)}

    result = {
        'result_code': 0,
        'msg': 'success',
        'folderUseMemberList': folderUseMemberList
    }
    return result
Esempio n. 9
0
def busca(request):
    # Pega o campo termo, que é o nome dado em base.html do campo de busca
    termo = request.GET.get('termo')

    if termo is None or not termo:
        messages.add_message(request, messages.ERROR,
                             'Você precisa digitar alguma coisa.')
        return redirect('index')

    # Concatenando os campos nome e sobrenome para poder procurar por partes
    # Seja do nome ou do sobrenome.
    campos = Concat('nome', Value(' '), 'sobrenome')

    # Cria o campo nome_completo e atribui o valor campos
    # Filtra pra mostrar só os que tiverem mostrar=True
    # Procura por qualquer letra que tenha no nome_completo
    # Ou procura por qualquer numero que tenha em telefone.
    contatos = Contato.objects.annotate(
        nome_completo=campos
    ).filter(
        mostrar=True
    ).filter(
        Q(nome_completo__icontains=termo) | Q(telefone__icontains=termo)
    )

    if int(len(contatos)) == 0:
        messages.add_message(request, messages.ERROR,
                             'Usuario nao encontrado.')
        return redirect('index')

    paginator = Paginator(contatos, 5)  # Mostra 5 contatos por página
    page_number = request.GET.get('page')
    contatos = paginator.get_page(page_number)

    return render(request, 'contatos/busca.html',
                  {
                      'contatos': contatos,

                  })
Esempio n. 10
0
class NotificationProfileAdmin(admin.ModelAdmin):
    list_display = ("get_str", "get_filters", "get_media", "active")
    list_filter = (
        "active",
        list_filter_factory("has phone number", lambda qs, yes_filter: qs.exclude(phone_number__isnull=yes_filter)),
    )
    search_fields = (
        "timeslot__name",
        "filters__name",
        "filters__filter_string",
        "user__first_name",
        "user__last_name",
        "user__username",
    )

    raw_id_fields = ("user", "timeslot")
    filter_horizontal = ("filters",)

    def get_str(self, notification_profile: NotificationProfile):
        return f"[{notification_profile.timeslot.user}] {notification_profile.timeslot}"

    get_str.short_description = "[User] Time slot"
    get_str.admin_order_field = Concat("timeslot__user", "timeslot__name")

    def get_filters(self, notification_profile: NotificationProfile):
        return format_html_join("", "<div>{}</div>", ((f,) for f in notification_profile.filters.all()))

    get_filters.short_description = "Filters"

    def get_media(self, notification_profile: NotificationProfile):
        return notification_profile.get_media_display()

    get_media.short_description = "Notification media"
    get_media.admin_order_field = "media"

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # Reduce number of database calls
        return qs.prefetch_related("timeslot__user", "filters")
Esempio n. 11
0
    def get_result(self, obj):
        is_valid = self.validate_context()
        if not is_valid:
            return PortInstallation.objects.none()
        today_day = datetime.datetime.now().day
        last_12_months = datetime.datetime.now(
            tz=datetime.timezone.utc) - datetime.timedelta(
                days=int(today_day) + 365)
        result = PortInstallation.objects \
            .only('id') \
            .filter(port__iexact=self.port_name, submission__timestamp__gte=last_12_months) \
            .annotate(datetime=TruncMonth('submission__timestamp')) \
            .order_by('datetime') \
            .annotate(
                m=Cast(ExtractMonth('datetime'), CharField()),
                y=Cast(ExtractYear('datetime'), CharField()),
                month=Concat('y', Value(','), 'm')
            ) \
            .values(*self.values) \
            .annotate(count=Count('submission__user_id', distinct=True))

        return result
Esempio n. 12
0
def universal_transaction_matview_annotations():
    annotation_fields = {
        "action_date_fiscal_year":
        FiscalYear("action_date"),
        "treasury_accounts_funding_this_award":
        StringAgg(
            "transaction__award__financial_set__treasury_account__tas_rendering_label",
            ";",
            distinct=True),
        "federal_accounts_funding_this_award":
        StringAgg(
            "transaction__award__financial_set__treasury_account__federal_account__federal_account_code",
            ";",
            distinct=True,
        ),
        "usaspending_permalink":
        Concat(
            Value(AWARD_URL),
            Func(F("transaction__award__generated_unique_award_id"),
                 function="urlencode"), Value("/")),
    }
    return annotation_fields
Esempio n. 13
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        name = self.request.GET["name"]

        people = None
        message = None

        if name:
            people = (Person.objects.annotate(full_name_search=Concat(
                "first_name", Value(" "), "last_name")).filter(
                    full_name_search__icontains=name).exclude(
                        pk=context["profile"].pk)[:10])

            if not people:
                message = f'No search results for name "{name}"'
        else:
            message = "Please enter a name"

        context.update(people=people, message=message)

        return context
Esempio n. 14
0
def List(dto_drml, superadmin=False):
    db_query = User.objects

    if not superadmin:
        db_query = db_query.exclude(id=1)

    db_query = db_query.annotate(
        apellido_nombre=Concat(F('last_name'), Value(' '), F('first_name')))
    int_total_rows = db_query.count()
    db_query = dto_drml.FilterList(db_query)
    db_query = dto_drml.SortList(db_query)
    int_total_rows_filtered = db_query.count()
    db_query = dto_drml.LimitList(db_query)

    serialized = UserSerializer(db_query,
                                many=True,
                                fields=(dto_drml.fields),
                                depth=(dto_drml.depth))

    return DataTransferResultSet(serialized.data, int_total_rows_filtered,
                                 int_total_rows, dto_drml.page,
                                 dto_drml.pageSize)
Esempio n. 15
0
 def formfield_for_foreignkey(self, db_field, request, **kwargs):
     if db_field.name == 'model':
         queryset = ContentType.objects.all().annotate(
             full_name=Concat(F('app_label'), Value('.'), F('model')))
         options = get_options()
         if not options.get('models', []):
             models = [
                 '%s.%s' % (m._meta.app_label, m._meta.model_name)
                 for m in apps.get_models()
             ]
             queryset = queryset.filter(full_name__in=models).exclude(
                 full_name__in=[
                     x.lower() for x in options.get('except', [])
                 ])
         else:
             queryset = queryset.filter(full_name__in=[
                 m.lower() for m in options.get('models', [])
             ])
         kwargs['queryset'] = queryset.order_by('model')
     return super(ImportJobAdmin,
                  self).formfield_for_foreignkey(db_field, request,
                                                 **kwargs)
Esempio n. 16
0
def is_not_yet_valid(app_label='ssl_cert_tracker',
                     model_name='sslcertificate'):
    """
    :returns:

        a :class:`django.db.models.query.QuerySet` based on the
        :class:`ssl_cert_tracker.models.SslCertificate`

        The :class:`django.db.models.query.QuerySet` returned by this function
        is:

        * `filtered
          <https://docs.djangoproject.com/en/2.2/ref/models/querysets/"""\
          """#filter>`__
          to show only the :attr:`State.NOT_YET_VALID` `SSL` certificates

        * `annotated
          <https://docs.djangoproject.com/en/2.2/ref/models/querysets/"""\
          """#annotate>`__
          with the :attr:`STATE_FIELD` in a field named `state`, and a
          :class:`django.db.models.BigIntegerField` field named
          'will_become_valid_in_x_days'

        * ordered descending on the 'will_become_valid_in_x_days' field
    """
    queryset = get_ssl_base_queryset(app_label, model_name).\
        annotate(state=STATE_FIELD).filter(state=State.NOT_YET_VALID).\
        annotate(mysql_now=Now()).\
        annotate(will_become_valid_in_x_days=DateDiff(
            F('not_before'), F('mysql_now'))).\
        annotate(will_become_valid_in_x_days_cast=Cast(
            'will_become_valid_in_x_days', CharField())).\
        annotate(alert_body=Concat(
            Value('SSL Certificate will become valid in ', TextField()),
            F('will_become_valid_in_x_days_cast'),
            Value(' days', TextField()), output_field=TextField())).\
        order_by('-will_become_valid_in_x_days')

    return queryset
Esempio n. 17
0
 def find_schema_by_reference(reference, as_excluded=False):
     if reference in settings.TENANTS and reference != "default" and allow_static:
         return reference
     elif reference == clone_reference:
         return reference
     elif dynamic_ready and TenantModel.objects.filter(
             schema_name=reference).exists() and allow_dynamic:
         return reference
     else:
         local = []
         if allow_static:
             local += [
                 schema_name
                 for schema_name, data in settings.TENANTS.items()
                 if schema_name not in ["public", "default"] and any(
                     x for x in data["DOMAINS"]
                     if x.startswith(reference))
             ]
         if dynamic_ready and allow_dynamic:
             local += (TenantModel.objects.annotate(route=Concat(
                 "domains__domain",
                 V("/"),
                 "domains__folder",
                 output_field=CharField())).filter(
                     Q(schema_name=reference)
                     | Q(domains__domain__istartswith=reference)
                     | Q(route=reference)).distinct().values_list(
                         "schema_name", flat=True))
         if not local:
             message = "No schema found for '%s' (excluded)" if as_excluded else "No schema found for '%s'"
             raise CommandError(message % reference)
         if len(local) > 1:
             message = (
                 "More than one tenant found for schema '%s' by domain (excluded), "
                 "please, narrow down the filter" if as_excluded else
                 "More than one tenant found for schema '%s' by domain, please, narrow down the filter"
             )
             raise CommandError(message % reference)
         return local[0]
Esempio n. 18
0
def ANNOTATE_BREW_NUMBER(qs: QuerySet,
                         annotate_name: str = 'brew_number') -> QuerySet:
    """
    Annotates QuerySet `qs` with name `annotate_name` (defaults to "brew_number")

    :param qs: BaseBatch QuerySet to annotate
    :type qs: QuerySet
    :param annotate_name: Name to provide for the annotation.  Defaults to `brew_number`
    :type annotate_name: str
    :return: Annotated QuerySet
    :rtype: QuerySet
    """
    """  Depreciated by below
    annotate_dict = {annotate_name: Cast(Case(
        When(__tbatch=1, then=Concat('year', Value('000'), 'batch')),
        When(__tbatch=2, then=Concat('year', Value('00'), 'batch')),
        When(__tbatch=3, then=Concat('year', Value('0'), 'batch')),
        default=Concat('year', 'batch')), output_field=DecimalField(max_digits=6, decimal_places=0)
    )}
    
    # Take the 'batch' field on BaseBatch, cast it to a CharField `__tbatch`.  The annotate_dict will
    # determine how many 0s to insert based on the length of `__tbatch`, and concat that with `year` field
    return qs.annotate(__tbatch=Length(Cast('batch', CharField(max_length=4)))).annotate(**annotate_dict)
    """

    # The use of `annotate_name` allows the field name to be passed to the queryset.  Otherwise, the name would be constant
    annotate_dict = {
        annotate_name:
        Cast(Concat(Right(
            Cast(ExtractYear('date'), output_field=CharField(max_length=4)),
            2),
                    LPad(Cast('batch', output_field=CharField(max_length=4)),
                         4,
                         Value('0'),
                         output_field=CharField(max_length=4)),
                    output_field=DecimalField(max_digits=6, decimal_places=0)),
             output_field=DecimalField(max_digits=6, decimal_places=0))
    }
    return qs.annotate(**annotate_dict)
Esempio n. 19
0
    def get_queryset(self):
        reviewers_physical_person = list(Reviewer.objects.all().values_list(
            'person', flat=True))

        force_include = self.request.GET.get('force_include')
        if force_include:
            force_include = int(force_include)

            try:
                reviewers_physical_person.remove(force_include)
            except ValueError:
                pass

        qs = PhysicalPerson.objects.\
            exclude(id__in=reviewers_physical_person). \
            annotate(full_name=Concat('first_name', V(' '), 'surname'))

        if self.q:
            qs = qs.filter(full_name__icontains=self.q)

        qs = qs.order_by('full_name')
        return qs
    def get_queryset(self):
        q_set = super(ProjectDataView, self).get_queryset()

        q_set = q_set.annotate(num_tasks=Count('tasks'))
        q_set = q_set.annotate(
            num_tasks_complete=Count('tasks', filter=Q(tasks__complete=True)))

        q_set = q_set.annotate(
            ajax_completion=Concat('num_tasks_complete',
                                   Value(" / "),
                                   'num_tasks',
                                   output_field=CharField()))

        q_set = q_set.annotate(
            ajax_status=Case(When(complete=True, then=Value('Completed')),
                             When(Q(deadline=None)
                                  | Q(deadline__gt=datetime.date.today()),
                                  then=Value('Incomplete')),
                             default=Value('Overdue'),
                             output_field=CharField()))

        return q_set
Esempio n. 21
0
    def q_filter(self, queryset, name, val):
        try:
            val=val.replace("'", '"')
            filter_q =Q()
            for key, val in json.loads(val).items():
                if key in ['created_on__date__range', 'contract_end_date__range']:

                    q_obj = Q(**{key:val[0].split(",")}) 
                else:
                    
                    q_obj = Q(**{key:val[0]})
                if val[1]=="or":
                    filter_q =  filter_q | q_obj
                else:
                    filter_q =  filter_q & q_obj
        except Exception as e:
            print("Exception in filter", e)
            return queryset
        return queryset.annotate(
                full_name=Concat(
                    F('first_name'), Value(" "), F('middle_name'), Value(" "), F('last_name'))
            ).filter(filter_q)
Esempio n. 22
0
def search(request):
    """
    A view that fuzzy-searches products, brands, ingredients given user input
    """
    if request.method == 'POST':
        form = SearchForm(request.POST)

        if form.is_valid():
            search_input = form.cleaned_data['search_input']

            p = set(Product.objects.annotate(
                querystr=Concat(
                    F('brand__name'),
                    F('name'),
                    F('ingredients__name'))
                ).filter(querystr__icontains=search_input))

            return render(request, 'searched.html', {'productdata': p})
    else:
        form = SearchForm()

    return render(request, 'search.html', {'form': form})
Esempio n. 23
0
    def get(self, request):
        pubs = Publication.api.primary(**visualization_query_filter(request)). \
            annotate(given_name=F('creators__given_name'), family_name=F('creators__family_name')).\
            values('given_name','family_name').\
            order_by('given_name', 'family_name').\
            annotate(published_count=Count('given_name'),
                     code_availability_count=models.Sum(models.Case(
                                                      models.When(~Q(code_archive_url=''), then=1),
                                                      default=0,
                                                      output_field=models.IntegerField())),
                     name=Concat('given_name', V(' '), 'family_name')).\
            values('name', 'published_count', 'code_availability_count', 'given_name', 'family_name').\
            order_by('-published_count')

        paginator = CatalogPagination()
        result_page = paginator.paginate_queryset(pubs, request)
        serializer = AuthorAggregrationSerializer(result_page, many=True)
        response = paginator.get_paginated_response(serializer.data)
        response['relation'] = RelationClassifier.AUTHOR.value
        return Response(
            {'json': dumps(response)},
            template_name="visualization/publication_relationlist.html")
Esempio n. 24
0
 def _stickiness(self, action: Action, filters: Dict[Any, Any],
                 request: request.Request):
     events = Event.objects.filter_by_action(action)\
         .filter(self._filter_events(request))\
         .annotate(day=functions.TruncDay('timestamp'))\
         .annotate(distinct_person_day=Concat('person_id', 'day', output_field=TextField()))\
         .order_by('distinct_person_day')\
         .distinct('distinct_person_day')
     date_from, date_to = self._get_dates_from_request(request)
     people: Dict[int, int] = {}
     for event in events:
         if not people.get(event.person_id):
             people[event.person_id] = 0
         people[event.person_id] += 1
     labels = []
     data = []
     for day in range(1, (date_to - date_from).days + 2):
         label = '{} day{}'.format(day, 's' if day > 1 else '')
         labels.append(label)
         data.append(
             len([key for key, value in people.items() if value == day]))
     return {'labels': labels, 'data': data}
Esempio n. 25
0
class SearchCompanyExportAPIView(SearchCompanyAPIViewMixin,
                                 SearchExportAPIView):
    """Company search export view."""

    queryset = DBCompany.objects.annotate(
        link=get_front_end_url_expression('company', 'pk'),
        upper_headquarter_type_name=Upper('headquarter_type__name'),
        sector_name=get_sector_name_subquery('sector'),
        # get company.turnover if set else company.turnover_range
        turnover_value=Case(
            When(
                turnover__isnull=False,
                then=Concat(Value('$'), 'turnover'),
            ),
            default='turnover_range__name',
            output_field=CharField(),
        ),
        # get company.number_of_employees if set else company.employee_range
        number_of_employees_value=Case(
            When(
                number_of_employees__isnull=False,
                then=Cast('number_of_employees', CharField()),
            ),
            default='employee_range__name',
            output_field=CharField(),
        ),
    )
    field_titles = {
        'name': 'Name',
        'link': 'Link',
        'sector_name': 'Sector',
        'address_country__name': 'Country',
        'uk_region__name': 'UK region',
        'archived': 'Archived',
        'created_on': 'Date created',
        'number_of_employees_value': 'Number of employees',
        'turnover_value': 'Annual turnover',
        'upper_headquarter_type_name': 'Headquarter type',
    }
Esempio n. 26
0
    def get_queryset(self):
        q = self.request.GET.get('q')
        sort = self.request.GET.get('sort')

        manager = self.get_serializer().Meta.model.objects

        if self.request.user.is_authenticated:
            queryset = manager.filter(
                Q(brand__isnull=False) | Q(created_by=self.request.user))
        else:
            queryset = manager.filter(brand__isnull=False)

        if q:
            queryset = queryset.annotate(
                full_name=Concat('brand__name', Value(' '), 'name'),
                distance=TrigramDistance('full_name', q)).filter(
                    Q(distance__lte=.8)
                    | Q(full_name__icontains=q)).order_by('distance')[:10]
        elif sort == "az":
            queryset = queryset.order_by(Lower('brand__name'), Lower('name'))

        return queryset
Esempio n. 27
0
    def annotations(self):
        """Create dictionary for query annotations.

        Returns:
            (Dict): query annotations dictionary

        """
        units_fallback = self._mapper.report_type_map.get('cost_units_fallback')
        annotations = {
            'date': self.date_trunc('usage_start'),
            'cost_units': Coalesce(self._mapper.cost_units_key, Value(units_fallback))
        }
        if self._mapper.usage_units_key:
            units_fallback = self._mapper.report_type_map.get('usage_units_fallback')
            annotations['usage_units'] = Coalesce(self._mapper.usage_units_key,
                                                  Value(units_fallback))

        # { query_param: database_field_name }
        fields = self._mapper.provider_map.get('annotations')
        for q_param, db_field in fields.items():
            annotations[q_param] = Concat(db_field, Value(''))
        return annotations
Esempio n. 28
0
class MissionListView(OceanographyAccessRequiredMixin, FilterView):
    template_name = "oceanography/mission_list.html"
    filterset_class = filters.MissionFilter
    queryset = shared_models.Cruise.objects.annotate(search_term=Concat(
        'mission_name', 'mission_number', output_field=TextField())).order_by(
            "-start_date", "mission_number")

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['my_object'] = shared_models.Cruise.objects.first()
        context["field_list"] = [
            'institute',
            'mission_number',
            'mission_name',
            'vessel',
            'chief_scientist',
            'start_date',
            'end_date',
            'meds_id',
            'season',
        ]
        return context
Esempio n. 29
0
def refresh_user_participants_cache(postalhistory: PostalHistory, save=False):
    try:
        postalhistory.attributes["user_cache"] = dict(
            count=postalhistory.postalhistoryuser_set.count(),
            list=list(postalhistory.postalhistoryuser_set.all().annotate(
                full_name=Concat("user__last_name", Value(
                    " "), "user__first_name")).values("user_id", "full_name")),
        )
        postalhistory.attributes["user_cache"]["repr"] = (",".join(
            list(
                map(
                    lambda c: c["full_name"],
                    postalhistory.attributes["user_cache"]["list"],
                ))) or None)
        if save:
            postalhistory.save()
    except:
        logging.warning(
            f"could not refresh user cache for postalhistory: {postalhistory.pk}"
        )
    finally:
        return postalhistory
Esempio n. 30
0
    def statistics_view(self, request):
        try:
            cl = self.get_changelist_instance(request)
        except IncorrectLookupParameters:
            if ERROR_FLAG in request.GET:
                return SimpleTemplateResponse("admin/invalid_setup.html", {
                    "title": _("Database error"),
                })
            return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1")

        chart_data = (cl.get_queryset(request).exclude(
            meta__subscriptions__NSP__date__isnull=True).annotate(
                subscription_datetime=Func(
                    "meta",
                    Value("subscriptions"),
                    Value("NSP"),
                    Value("date"),
                    function="jsonb_extract_path_text",
                )).annotate(subscription_date=Concat(
                    Substr("subscription_datetime", 1, 10), Value(
                        "T00:00:00Z"))).values("subscription_date").annotate(
                            y=Count("id")).order_by("subscription_date"))

        context = {
            **self.admin_site.each_context(request),
            "title": "Statistiques",
            "opts": self.model._meta,
            "cl": cl,
            "media": self.media,
            "preserved_filters": self.get_preserved_filters(request),
            "chart_data": json.dumps(list(chart_data), cls=DjangoJSONEncoder),
        }

        return TemplateResponse(
            request,
            "admin/people/person/statistics.html",
            context,
        )