當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。