本文整理汇总了Python中django.db.models.TextField方法的典型用法代码示例。如果您正苦于以下问题:Python models.TextField方法的具体用法?Python models.TextField怎么用?Python models.TextField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.TextField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: define_projection_record_class
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def define_projection_record_class(self):
class ProjectionRecord(models.Model):
uid = models.BigAutoField(primary_key=True)
# Sequence ID (e.g. an entity or aggregate ID).
projection_id = models.UUIDField()
# State of the item (serialized dict, possibly encrypted).
state = models.TextField()
class Meta:
db_table = "projections"
app_label = "projections"
managed = False
self.projection_record_class = ProjectionRecord
示例2: as_vector
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def as_vector(self, texts, for_autocomplete=False):
"""
Converts an array of strings into a SearchVector that can be indexed.
"""
texts = [(text.strip(), weight) for text, weight in texts]
texts = [(text, weight) for text, weight in texts if text]
if not texts:
return EMPTY_VECTOR
search_config = self.autocomplete_config if for_autocomplete else self.config
return ADD([
SearchVector(Value(text, output_field=TextField()), weight=weight, config=search_config)
for text, weight in texts
])
示例3: __init__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def __init__(self, *expressions, **kwargs):
separator = kwargs.pop("separator", ",")
if len(kwargs) > 0:
raise ValueError(
"Invalid keyword arguments for ConcatWS: {}".format(
",".join(kwargs.keys())
)
)
if len(expressions) < 2:
raise ValueError("ConcatWS must take at least two expressions")
if not hasattr(separator, "resolve_expression"):
separator = Value(separator)
# N.B. if separator is "," we could potentially use list field
output_field = TextField()
super().__init__(separator, *expressions, output_field=output_field)
示例4: instantiate_object_id_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField):
"""
Instantiates and returns a model field for FieldHistory.object_id.
object_id_class_or_tuple may be either a Django model field class or a
tuple of (model_field, kwargs), where kwargs is a dict passed to
model_field's constructor.
"""
if isinstance(object_id_class_or_tuple, (list, tuple)):
object_id_class, object_id_kwargs = object_id_class_or_tuple
else:
object_id_class = object_id_class_or_tuple
object_id_kwargs = {}
if not issubclass(object_id_class, models.fields.Field):
raise TypeError('settings.%s must be a Django model field or (field, kwargs) tuple' % OBJECT_ID_TYPE_SETTING)
if not isinstance(object_id_kwargs, dict):
raise TypeError('settings.%s kwargs must be a dict' % OBJECT_ID_TYPE_SETTING)
return object_id_class(db_index=True, **object_id_kwargs)
示例5: setUp
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def setUp(self):
self.models_py = """
from django.db import models
class Tmp4Wlpvd0C(models.Model):
timestamp = models.TextField(db_column='Timestamp', blank=True, null=True)
question_with_short_answer_field = models.TextField(db_column='Question with short answer?')
question_with_long_answer_field = models.TextField(db_column='Question with long answer?')
checkbox_field = models.TextField(db_column='Checkbox?')
option_with_dropdown_field = models.TextField(db_column='Option with dropdown?')
multiple_choice_field = models.TextField(db_column='Multiple choice?')
field_numeric_linear_scale_field = models.TextField(db_column=' Numeric linear scale?')
multiple_choice_grid_row1_field = models.TextField(db_column='Multiple choice grid? [row1]')
multiple_choice_grid_row2_field = models.TextField(db_column='Multiple choice grid? [row2]')
checkbox_grid_row1_field = models.TextField(db_column='Checkbox grid? [row1]')
checkbox_grid_row2_field = models.TextField(db_column='Checkbox grid? [row2]')
what_date_field = models.DateField(db_column='What date?')
what_time_field = models.TextField(db_column='What time?')
"""
示例6: test_custom_default_manager_added_to_the_model_state
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def test_custom_default_manager_added_to_the_model_state(self):
"""
When the default manager of the model is a custom manager,
it needs to be added to the model state.
"""
new_apps = Apps(['migrations'])
custom_manager = models.Manager()
class Author(models.Model):
objects = models.TextField()
authors = custom_manager
class Meta:
app_label = 'migrations'
apps = new_apps
project_state = ProjectState.from_apps(new_apps)
author_state = project_state.models['migrations', 'author']
self.assertEqual(author_state.managers, [('authors', custom_manager)])
示例7: schema_type_from_model_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def schema_type_from_model_field(field):
field_class = field.__class__
if field_class == models.FloatField:
return 'number', None
elif field_class in [models.CharField, models.TextField]:
return 'string', None
elif field_class == models.DateTimeField:
return 'string', 'date-time'
elif field_class == models.BooleanField:
return 'boolean', None
elif field_class == models.ForeignKey:
return 'string', 'url'
else:
raise NotImplementedError('Field type %s not recognized' % field_class)
# TODO: this should get the URL dynamically
示例8: sanitize_field_value
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def sanitize_field_value(cls, field_name, value):
'''Converts the given value to the correct python tyhttp://localhost:8080/people/1pe, for instance if
the field is supposed to be a float field and the string "23" is given,
it will be converted to 23.0
NOTE - this currently only works for vanilla model fields, which serves
our purposes for now'''
field = cls.model._meta.get_field_by_name(field_name)[0]
field_class = field.__class__
if field_class == models.ForeignKey:
lookup = lookup_associated_model_object(value)
if lookup is None:
raise BadRequestException(
"The url to the given resource does not exist.")
return lookup
# TextField missing to_python in Django 1.6
elif field_class == models.TextField:
if isinstance(value, six.string_types) or value is None:
return value
return smart_text(value)
return field.to_python(value)
示例9: archive_log
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
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')
示例10: test_max_length_warning
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def test_max_length_warning(self):
class Model(models.Model):
value = models.TextField(db_index=True)
field = Model._meta.get_field('value')
field_type = field.db_type(connection)
self.assertEqual(field.check(), [
DjangoWarning(
'%s does not support a database index on %s columns.'
% (connection.display_name, field_type),
hint=(
"An index won't be created. Silence this warning if you "
"don't care about it."
),
obj=field,
id='fields.W162',
)
])
示例11: test
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def test(cls, field, request, params, model, admin_view, field_path):
return (
isinstance(field, models.CharField)
and field.max_length > 20
or isinstance(field, models.TextField)
)
示例12: __init__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def __init__(self, source, *args, **kwargs):
self.source = source
kwargs.setdefault('editable', False)
super(TextField, self).__init__(*args, **kwargs)
示例13: deconstruct
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def deconstruct(self):
name, path, args, kwargs = super(TextField, self).deconstruct()
args.append(self.source)
return name, path, args, kwargs
示例14: allow_search_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def allow_search_fields(self, exclude=None, include=None):
opts = self.opts
def construct_search(model):
exclude = [f.name for f in opts.fields if getattr(f, 'choices')]
fields = model._meta.fields
_fields = []
for f in fields:
if isinstance(f, models.CharField) and f.name not in exclude:
_fields.append(f.name + '__icontains')
return _fields
if not exclude:
exclude = ['onidc', 'slug', 'created', 'modified']
exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])
fields = construct_search(self.model)
for f in opts.fields:
if exclude and f.name in exclude:
continue
if isinstance(f, models.ForeignKey):
submodel = f.related_model
for sub in submodel._meta.fields:
if exclude and sub.name in exclude:
continue
if isinstance(
sub, models.CharField) and not getattr(
sub, 'choices'):
fields.append(f.name + '__' + sub.name + '__icontains')
if isinstance(f, (models.CharField, models.TextField)):
fields.append(f.name + '__icontains')
return fields
示例15: display_for_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import TextField [as 别名]
def display_for_field(value, field, html=True, only_date=True):
if getattr(field, 'flatchoices', None):
if html and field.name == 'color' and value:
return make_color_icon(value)
return dict(field.flatchoices).get(value, '')
elif html and (isinstance(field, (models.BooleanField, models.NullBooleanField))):
return make_boolean_icon(value)
elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
boolchoice = {False: "否", True: "是"}
return boolchoice.get(value)
elif value is None:
return ""
elif isinstance(field, models.DecimalField):
return formats.number_format(value, field.decimal_places)
elif isinstance(field, (models.IntegerField, models.FloatField)):
return formats.number_format(value)
elif isinstance(field, models.ForeignKey) and value:
rel_obj = field.related_model.objects.get(pk=value)
if html and COLOR_FK_FIELD and isinstance(rel_obj, Option):
text_color = rel_obj.color
if not text_color:
text_color = 'text-info'
safe_value = format_html(
'<span class="text-{}">{}</span>', text_color, rel_obj.text)
return safe_value
return force_text(rel_obj)
elif isinstance(field, models.TextField) and value:
return force_text(value)
elif isinstance(field, models.DateTimeField):
if only_date:
return formats.date_format(value)
return formats.localize(timezone.template_localtime(value))
elif isinstance(field, (models.DateField, models.TimeField)):
return formats.localize(value)
elif isinstance(field, models.FileField) and value:
return format_html('<a href="{}">{}</a>', value.url, value)
else:
return display_for_value(value)