当前位置: 首页>>代码示例>>Python>>正文


Python functions.Length方法代码示例

本文整理汇总了Python中django.db.models.functions.Length方法的典型用法代码示例。如果您正苦于以下问题:Python functions.Length方法的具体用法?Python functions.Length怎么用?Python functions.Length使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.models.functions的用法示例。


在下文中一共展示了functions.Length方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_queryset

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def get_queryset(self, base_queryset=RoundsAndLabsQueryset):
        funds = ApplicationBase.objects.filter(path=OuterRef('parent_path'))

        return base_queryset(self.model, using=self._db).type(SubmittableStreamForm).annotate(
            lead=Coalesce(
                F('roundbase__lead__full_name'),
                F('labbase__lead__full_name'),
            ),
            start_date=F('roundbase__start_date'),
            end_date=F('roundbase__end_date'),
            parent_path=Left(F('path'), Length('path') - ApplicationBase.steplen, output_field=CharField()),
            fund=Subquery(funds.values('title')[:1]),
            lead_pk=Coalesce(
                F('roundbase__lead__pk'),
                F('labbase__lead__pk'),
            ),
        ) 
开发者ID:OpenTechFund,项目名称:hypha,代码行数:19,代码来源:applications.py

示例2: test_partial_gin_index_with_tablespace

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def test_partial_gin_index_with_tablespace(self):
        with register_lookup(CharField, Length):
            index_name = 'char_field_gin_partial_idx'
            index = GinIndex(
                fields=['field'],
                name=index_name,
                condition=Q(field__length=40),
                db_tablespace='pg_default',
            )
            with connection.schema_editor() as editor:
                editor.add_index(CharFieldModel, index)
                self.assertIn('TABLESPACE "pg_default" ', str(index.create_sql(CharFieldModel, editor)))
            constraints = self.get_constraints(CharFieldModel._meta.db_table)
            self.assertEqual(constraints[index_name]['type'], 'gin')
            with connection.schema_editor() as editor:
                editor.remove_index(CharFieldModel, index)
            self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table)) 
开发者ID:nesdis,项目名称:djongo,代码行数:19,代码来源:test_indexes.py

示例3: get_queried_genes

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def get_queried_genes(query, max_results):
    matching_genes = GeneInfo.objects.filter(
        Q(gene_id__icontains=query) | Q(gene_symbol__icontains=query)
    ).only('gene_id', 'gene_symbol').order_by(Length('gene_symbol').asc()).distinct()
    return [{'gene_id': gene.gene_id, 'gene_symbol': gene.gene_symbol} for gene in matching_genes[:max_results]] 
开发者ID:macarthur-lab,项目名称:seqr,代码行数:7,代码来源:gene_utils.py

示例4: get_queryset

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def get_queryset(self):
        return (
            super().get_queryset()
            .filter(url__startswith='/privacy-policy-')
            .annotate(
                version=dbf.Substr(  # Poor man's regex ^/privacy-policy-(.+)/$
                    dbf.Substr('url', 1, dbf.Length('url') - 1, output_field=models.CharField()),
                    len('/privacy-policy-') + 1)
            )
        ) 
开发者ID:tejoesperanto,项目名称:pasportaservo,代码行数:12,代码来源:managers.py

示例5: get_bot_config_size

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def get_bot_config_size(bot_profile: UserProfile, key: Optional[str]=None) -> int:
    if key is None:
        return BotConfigData.objects.filter(bot_profile=bot_profile) \
                                    .annotate(key_size=Length('key'), value_size=Length('value')) \
                                    .aggregate(sum=Sum(F('key_size')+F('value_size')))['sum'] or 0
    else:
        try:
            return len(key) + len(BotConfigData.objects.get(bot_profile=bot_profile, key=key).value)
        except BotConfigData.DoesNotExist:
            return 0 
开发者ID:zulip,项目名称:zulip,代码行数:12,代码来源:bot_config.py

示例6: get_bot_storage_size

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def get_bot_storage_size(bot_profile: UserProfile, key: Optional[str]=None) -> int:
    if key is None:
        return BotStorageData.objects.filter(bot_profile=bot_profile) \
                                     .annotate(key_size=Length('key'), value_size=Length('value')) \
                                     .aggregate(sum=Sum(F('key_size')+F('value_size')))['sum'] or 0
    else:
        try:
            return len(key) + len(BotStorageData.objects.get(bot_profile=bot_profile, key=key).value)
        except BotStorageData.DoesNotExist:
            return 0 
开发者ID:zulip,项目名称:zulip,代码行数:12,代码来源:bot_storage.py

示例7: make_text_units_query

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def make_text_units_query(project_id):
    filters = dict(unit_type='paragraph', text_len__gt=99)
    if project_id:
        filters['document__project_id'] = project_id
    return TextUnit.objects.annotate(text_len=Length('textunittext__text')).filter(
        **filters).order_by('pk') 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:8,代码来源:similarity_metrics.py

示例8: _refresh_title_norms

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def _refresh_title_norms(self):
        """
        Refreshes the value of the title_norm field.

        This needs to be set to 'lavg/ld' where:
         - lavg is the average length of titles in all documents (also in terms)
         - ld is the length of the title field in this document (in terms)
        """

        lavg = self.entries.annotate(title_length=Length('title')).aggregate(Avg('title_length'))['title_length__avg']
        self.entries.annotate(title_length=Length('title')).filter(title_length__gt=0).update(title_norm=lavg / F('title_length')) 
开发者ID:wagtail,项目名称:wagtail,代码行数:13,代码来源:backend.py

示例9: get_sitewide_message

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def get_sitewide_message(slug="welcome_message", lang=None):
        """
        Returns a sitewide message based on its slug and the specified language.
        If the language is not specified, it will use the current language.
        If there are no results found, it falls back on the global version.
        It doesn't exist at all, it returns None.
        :param slug: str
        :param lang: str|None
        :return: MarkupField|None
        """

        # Get default value if lang is not specified
        language = lang if lang else get_language()

        # Let's retrieve messages where slug is either:
        #   - "<slug>_<locale>"
        #   - "<slug>"
        # We order the results by the length of the slug to be sure
        # localized version comes first.
        sitewide_message = SitewideMessage.objects\
            .filter(
                Q(slug="{}_{}".format(slug, language)) |
                Q(slug="{}".format(slug)))\
            .order_by(Length("slug").desc())\
            .first()

        if sitewide_message is not None:
            return sitewide_message.body

        return None 
开发者ID:kobotoolbox,项目名称:kpi,代码行数:32,代码来源:i18n.py

示例10: test_if_basic

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def test_if_basic(self):
        Alphabet.objects.create(d="String")
        Alphabet.objects.create(d="")
        Alphabet.objects.create(d="String")
        Alphabet.objects.create(d="")

        results = list(
            Alphabet.objects.annotate(has_d=If(Length("d"), Value(True), Value(False)))
            .order_by("id")
            .values_list("has_d", flat=True)
        )
        assert results == [True, False, True, False] 
开发者ID:adamchainz,项目名称:django-mysql,代码行数:14,代码来源:test_functions.py

示例11: test_regex_substr_filter

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def test_regex_substr_filter(self):
        Author.objects.create(name="Euripides")
        Author.objects.create(name="Frank Miller")
        Author.objects.create(name="Sophocles")
        qs = list(
            Author.objects.annotate(name_has_space=Length(RegexpSubstr("name", r"\s")))
            .filter(name_has_space=0)
            .order_by("id")
            .values_list("name", flat=True)
        )
        assert qs == ["Euripides", "Sophocles"] 
开发者ID:adamchainz,项目名称:django-mysql,代码行数:13,代码来源:test_functions.py

示例12: get_search_results

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def get_search_results(self, request, queryset, search_term):
        search_term = search_term.strip()
        if search_term:
            return queryset.filter(
                tag__startswith=search_term
            ).annotate(
                tag_length=Length('tag')
            ).order_by('tag_length'), False
        else:
            return queryset.none(), False 
开发者ID:simonw,项目名称:simonwillisonblog,代码行数:12,代码来源:admin.py

示例13: migrate_history_lines

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def migrate_history_lines(apps, schema_editor):
    HistoryLines = apps.get_registered_model('main', 'HistoryLines')
    qs = HistoryLines.objects.annotate(line_len=Length('line'))
    qs = qs.filter(line_len__gt=2048)
    lines = []
    for hist_line in qs:
        history = hist_line.history
        value = hist_line.line
        number = hist_line.line_number
        hist_line.delete()
        lines += [l for l in __bulking_lines(history, value, number, HistoryLines)]
    HistoryLines.objects.bulk_create(lines) 
开发者ID:vstconsulting,项目名称:polemarch,代码行数:14,代码来源:0046_auto_20180608_0658.py

示例14: test_basic

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def test_basic(self):
        Author.objects.create(name='John', alias='xyz')
        tests = (
            (Repeat('name', 0), ''),
            (Repeat('name', 2), 'JohnJohn'),
            (Repeat('name', Length('alias'), output_field=CharField()), 'JohnJohnJohn'),
            (Repeat(Value('x'), 3, output_field=CharField()), 'xxx'),
        )
        for function, repeated_text in tests:
            with self.subTest(function=function):
                authors = Author.objects.annotate(repeated_text=function)
                self.assertQuerysetEqual(authors, [repeated_text], lambda a: a.repeated_text, ordered=False) 
开发者ID:nesdis,项目名称:djongo,代码行数:14,代码来源:test_repeat.py

示例15: test_combined_with_length

# 需要导入模块: from django.db.models import functions [as 别名]
# 或者: from django.db.models.functions import Length [as 别名]
def test_combined_with_length(self):
        Author.objects.create(name='Rhonda', alias='john_smith')
        Author.objects.create(name='♥♣♠', alias='bytes')
        authors = Author.objects.annotate(filled=LPad('name', Length('alias'), output_field=CharField()))
        self.assertQuerysetEqual(
            authors.order_by('alias'),
            ['  ♥♣♠', '    Rhonda'],
            lambda a: a.filled,
        ) 
开发者ID:nesdis,项目名称:djongo,代码行数:11,代码来源:test_pad.py


注:本文中的django.db.models.functions.Length方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。