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


Python models.CharField方法代码示例

本文整理汇总了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 
开发者ID:adfinis-sygroup,项目名称:timed-backend,代码行数:23,代码来源:views.py

示例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 
开发者ID:Wenvki,项目名称:django-idcops,代码行数:22,代码来源:utils.py

示例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
        ),
    ] 
开发者ID:anexia-it,项目名称:django-rest-passwordreset,代码行数:22,代码来源:0002_pk_migration.py

示例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",
            ],
        ) 
开发者ID:edoburu,项目名称:sphinxcontrib-django,代码行数:22,代码来源:test_docstrings.py

示例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`)",
            ],
        ) 
开发者ID:edoburu,项目名称:sphinxcontrib-django,代码行数:18,代码来源:test_docstrings.py

示例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') 
开发者ID:ra-systems,项目名称:django-ra-erp,代码行数:19,代码来源:models.py

示例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")) 
开发者ID:byro,项目名称:byro,代码行数:22,代码来源:registration.py

示例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()
            ) 
开发者ID:SectorLabs,项目名称:django-localized-fields,代码行数:27,代码来源:test_slug_fields.py

示例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,
                ),
            }
        ) 
开发者ID:SectorLabs,项目名称:django-localized-fields,代码行数:21,代码来源:test_expressions.py

示例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'
        ] 
开发者ID:django-leonardo,项目名称:django-leonardo,代码行数:18,代码来源:admin.py

示例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")) 
开发者ID:javrasya,项目名称:django-river,代码行数:33,代码来源:orm_driver.py

示例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) 
开发者ID:dulacp,项目名称:django-accounting,代码行数:6,代码来源:fields.py

示例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) 
开发者ID:dulacp,项目名称:django-accounting,代码行数:9,代码来源:fields.py

示例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)
               ) 
开发者ID:stormsha,项目名称:StormOnline,代码行数:8,代码来源:filters.py

示例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__}) 
开发者ID:LuciferJack,项目名称:python-mysql-pool,代码行数:16,代码来源:validation.py


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