本文整理匯總了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'),
),
)
示例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))
示例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]]
示例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)
)
)
示例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
示例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
示例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')
示例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'))
示例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
示例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]
示例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"]
示例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
示例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)
示例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)
示例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,
)