本文整理汇总了Python中django.db.models.CharField方法的典型用法代码示例。如果您正苦于以下问题:Python models.CharField方法的具体用法?Python models.CharField怎么用?Python models.CharField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.CharField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_queryset
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def get_queryset(self):
date = self._extract_date()
user = self.request.user
queryset = get_user_model().objects.values("id")
queryset = queryset.annotate(date=Value(date, DateField()))
# last_reported_date filter is set, a date can only be calucated
# for users with either at least one absence or report
if date is None:
users_with_reports = Report.objects.values("user").distinct()
users_with_absences = Absence.objects.values("user").distinct()
active_users = users_with_reports.union(users_with_absences)
queryset = queryset.filter(id__in=active_users)
queryset = queryset.annotate(
pk=Concat("id", Value("_"), "date", output_field=CharField())
)
if not user.is_superuser:
queryset = queryset.filter(Q(id=user.id) | Q(supervisors=user))
return queryset
示例2: allow_search_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def allow_search_fields(cls, exclude=None):
opts = cls._meta
if not exclude:
exclude = ['onidc', 'slug', 'created', 'modified']
exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])
fields = []
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):
fields.append(f.name + '__icontains')
return fields
示例3: get_migrations_for_django_21_and_newer
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def get_migrations_for_django_21_and_newer():
return [
# remove primary key information from 'key' field
migrations.AlterField(
model_name='resetpasswordtoken',
name='key',
field=models.CharField(db_index=True, primary_key=False, max_length=64, unique=True, verbose_name='Key'),
),
# add a new id field
migrations.AddField(
model_name='resetpasswordtoken',
name='id',
field=models.AutoField(primary_key=True, serialize=False),
preserve_default=False,
),
migrations.RunPython(
populate_auto_incrementing_pk_field,
migrations.RunPython.noop
),
]
示例4: test_model_init_params
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def test_model_init_params(self):
"""Model __init__ gets all fields as params."""
lines = []
docstrings._add_model_fields_as_params(self.app, SimpleModel, lines)
self.assertEqual(
lines,
[
":param id: Id",
":type id: AutoField",
":param user: User",
":type user: ForeignKey to :class:`~django.contrib.auth.models.User`",
":param user2: User2",
":type user2: ForeignKey to"
" :class:`~sphinxcontrib_django.tests.test_docstrings.User2`",
":param user3: User3",
":type user3: ForeignKey to :class:`~django.contrib.auth.models.User`",
":param dummy_field: Dummy field",
":type dummy_field: CharField",
],
)
示例5: test_add_form_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def test_add_form_fields(self):
"""Form fields should be mentioned."""
lines = []
docstrings._add_form_fields(SimpleForm, lines)
self.assertEqual(
lines,
[
"**Form fields:**",
"",
"* ``user``: User (:class:`~django.forms.models.ModelChoiceField`)",
"* ``user2``: User2 (:class:`~django.forms.models.ModelChoiceField`)",
"* ``user3``: User3 (:class:`~django.forms.models.ModelChoiceField`)",
"* ``test1``: Test1 (:class:`~django.forms.fields.CharField`)",
"* ``test2``: Test2 (:class:`~django.forms.fields.CharField`)",
],
)
示例6: get_redirect_url_prefix
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def get_redirect_url_prefix(cls):
"""
Get the url for the change list of this model
:return: a string url
"""
return reverse('%s:%s_%s_changelist' % (
app_settings.RA_ADMIN_SITE_NAME, cls._meta.app_label, cls.get_class_name().lower()))
# class BasePersonInfo(BaseInfo):
# address = models.CharField(_('address'), max_length=260, null=True, blank=True)
# telephone = models.CharField(_('telephone'), max_length=130, null=True, blank=True)
# email = models.EmailField(_('email'), null=True, blank=True)
#
# class Meta:
# abstract = True
# # swappable = swapper.swappable_setting('ra', 'BasePersonInfo')
示例7: build_default_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def build_default_field(self, field, model):
choices = getattr(field, "choices", None)
if choices:
return forms.ChoiceField(
required=False,
label=_("Default value"),
choices=[(None, "-----------")] + list(choices),
)
if not (model is Member and field.name == "number"):
if isinstance(field, models.CharField):
return forms.CharField(required=False, label=_("Default value"))
elif isinstance(field, models.DecimalField):
return forms.DecimalField(
required=False,
label=_("Default value"),
max_digits=field.max_digits,
decimal_places=field.decimal_places,
)
elif isinstance(field, models.DateField):
return forms.CharField(required=False, label=_("Other/fixed date"))
示例8: test_populate_multiple_from_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def test_populate_multiple_from_fields():
"""Tests whether populating the slug from multiple fields works
correctly."""
model = get_fake_model(
{
"title": LocalizedField(),
"name": models.CharField(max_length=255),
"slug": LocalizedUniqueSlugField(
populate_from=("title", "name")
),
}
)
obj = model()
for lang_code, lang_name in settings.LANGUAGES:
obj.name = "swen"
obj.title.set(lang_code, "title %s" % lang_name)
obj.save()
for lang_code, lang_name in settings.LANGUAGES:
assert (
obj.slug.get(lang_code) == "title-%s-swen" % lang_name.lower()
)
示例9: setUpClass
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def setUpClass(cls):
"""Creates the test model in the database."""
super(LocalizedExpressionsTestCase, cls).setUpClass()
cls.TestModel1 = get_fake_model(
{"name": models.CharField(null=False, blank=False, max_length=255)}
)
cls.TestModel2 = get_fake_model(
{
"text": LocalizedField(),
"other": models.ForeignKey(
cls.TestModel1,
related_name="features",
on_delete=models.CASCADE,
),
}
)
示例10: owner_search_fields
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return [
field.name for field in User._meta.fields
if isinstance(field, models.CharField) and field.name != 'password'
]
示例11: get_available_approvals
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def get_available_approvals(self, as_user):
those_with_max_priority = With(
TransitionApproval.objects.filter(
workflow=self.workflow, status=PENDING
).values(
'workflow', 'object_id', 'transition'
).annotate(min_priority=Min('priority'))
)
workflow_objects = With(
self.wokflow_object_class.objects.all(),
name="workflow_object"
)
approvals_with_max_priority = those_with_max_priority.join(
self._authorized_approvals(as_user),
workflow_id=those_with_max_priority.col.workflow_id,
object_id=those_with_max_priority.col.object_id,
transition_id=those_with_max_priority.col.transition_id,
).with_cte(
those_with_max_priority
).annotate(
object_id_as_str=Cast('object_id', CharField(max_length=200)),
min_priority=those_with_max_priority.col.min_priority
).filter(min_priority=F("priority"))
return workflow_objects.join(
approvals_with_max_priority, object_id_as_str=Cast(workflow_objects.col.pk, CharField(max_length=200))
).with_cte(
workflow_objects
).filter(transition__source_state=getattr(workflow_objects.col, self.field_name + "_id"))
示例12: __init__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 64 )
kwargs['blank'] = True
models.CharField.__init__(self, *args, **kwargs)
示例13: pre_save
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def pre_save(self, model_instance, add):
if add or not getattr(model_instance, self.attname):
value = self._generate_uuid()
setattr(model_instance, self.attname, value)
return value
else:
return super(models.CharField, self).pre_save(model_instance, add)
示例14: test
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [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)
)
示例15: validate_field
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import CharField [as 别名]
def validate_field(self, errors, opts, f):
"""
MySQL has the following field length restriction:
No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.
"""
varchar_fields = (models.CharField,
models.CommaSeparatedIntegerField,
models.SlugField)
if isinstance(f, varchar_fields) and f.max_length > 255 and f.unique:
msg = ('"%(name)s": %(cls)s cannot have a "max_length" greater '
'than 255 when using "unique=True".')
errors.add(opts, msg % {'name': f.name,
'cls': f.__class__.__name__})