Top

telemeta.models.fields module

# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2010 Samalyse SARL
# Copyright (C) 2010-2015 Parisson SARL
#
# This file is part of Telemeta.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Olivier Guilyardi <olivier@samalyse.com>
#          Guillaume Pellerin <yomguy@parisson.com>

from __future__ import division

__all__ = ['DurationField', 'Duration', 'WeakForeignKey',
           'CharField', 'TextField', 'IntegerField', 'BooleanField',
           'DateTimeField', 'FileField', 'ForeignKey', 'FloatField', 'DateField',
           'RequiredFieldError',]

import datetime, re
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from south.modelsinspector import add_introspection_rules


class Duration(object):
    """Represent a time duration"""
    def __init__(self, *args, **kwargs):
        if len(args) and isinstance(args[0], datetime.timedelta):
            self._delta = datetime.timedelta(days=args[0].days, seconds=args[0].seconds)
        else:
            self._delta = datetime.timedelta(*args, **kwargs)

    def __decorate(self, method, other):
        if isinstance(other, Duration):
            res = method(other._delta)
        else:
            res = method(other)
        if type(res) == datetime.timedelta:
            return Duration(res)

        return res

    def __add__(self, other):
        return self.__decorate(self._delta.__add__, other)

    def __nonzero__(self):
        return self._delta.__nonzero__()

    def __str__(self):
        hours   = self._delta.days * 24 + self._delta.seconds / 3600
        minutes = (self._delta.seconds % 3600) / 60
        seconds = self._delta.seconds % 60

        return "%.2d:%.2d:%.2d" % (hours, minutes, seconds)

    def __unicode__(self):
        return self.__str__()

    @staticmethod
    def fromstr(str):
        if not str:
            return Duration()

        test = re.match('^([0-9]+)(?::([0-9]+)(?::([0-9]+))?)?$', str)
        if test:
            groups = test.groups()
            try:
                hours = minutes = seconds = 0
                if groups[0]:
                    hours = int(groups[0])
                    if groups[1]:
                        minutes = int(groups[1])
                        if groups[2]:
                            seconds = int(groups[2])

                return Duration(hours=hours, minutes=minutes, seconds=seconds)
            except TypeError:
                print groups
                raise
        else:
            raise ValueError("Malformed duration string: " + str)

    def as_seconds(self):
        return self._delta.days * 24 * 3600 + self._delta.seconds


def normalize_field(args, default_value=None):
    """Normalize field constructor arguments, so that the field is marked blank=True
       and has a default value by default.

       This behaviour can be disabled by passing the special argument required=True.

       The default value can also be overriden with the default=value argument.
       """
    required = False
    if args.has_key('required'):
        required = args['required']
        args.pop('required')

    args['blank'] = not required

    if not required:
        if not args.has_key('default'):
            if args.get('null'):
                args['default'] = None
            elif default_value is not None:
                args['default'] = default_value

    return args


class DurationField(models.Field):
    """Duration Django model field based on Django TimeField.
    Essentially the same as a TimeField, but with values over 24h allowed.

    The constructor arguments are also normalized with normalize_field().
    """

    description = _("Duration")

    __metaclass__ = models.SubfieldBase

    default_error_messages = {
        'invalid': _('Enter a valid duration in HH:MM[:ss] format.'),
    }

    def __init__(self, *args, **kwargs):
        super(DurationField, self).__init__(*args, **normalize_field(kwargs, '0'))

    def db_type(self, connection):
        return 'int'

    def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, int) or isinstance(value, long):
            return Duration(seconds=value)
        if isinstance(value, datetime.time):
            return Duration(hours=value.hour, minutes=value.minute, seconds=value.second)
        if isinstance(value, datetime.datetime):
            # Not usually a good idea to pass in a datetime here (it loses
            # information), but this can be a side-effect of interacting with a
            # database backend (e.g. Oracle), so we'll be accommodating.
            return self.to_python(value.time())
        else:
            value = str(value)
        try:
            return Duration.fromstr(value)
        except ValueError:
            raise exceptions.ValidationError(self.error_messages['invalid'])

    def get_prep_value(self, value):
        return self.to_python(value)

    def get_db_prep_value(self, value, connection=None, prepared=False):
        # Casts times into the format expected by the backend
        try:
            return value.as_seconds()
        except:
            return value

    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        if val is None:
            data = ''
        else:
            data = unicode(val)
        return data

    def formfield(self, **kwargs):
        defaults = {'form_class': forms.CharField}
        defaults.update(kwargs)
        return super(DurationField, self).formfield(**defaults)


class ForeignKey(models.ForeignKey):
    """The constructor arguments of this ForeignKey are normalized
    with normalize_field(), however the field is marked required by default
    unless it is allowed to be null."""

    def __init__(self, to, **kwargs):
        if not kwargs.has_key('required'):
            if not kwargs.get('null'):
                kwargs['required'] = True

        super(ForeignKey, self).__init__(to, **normalize_field(kwargs, 0))


class WeakForeignKey(ForeignKey):
    """A weak foreign key is the same as foreign key but without cascading
    delete. Instead the reference is set to null when the referenced record
    get deleted. This emulates the ON DELETE SET NULL sql behaviour.

    This field is automatically allowed to be null, there's no need to pass
    null=True.

    The constructor arguments are normalized with normalize_field() by the
    parent ForeignKey

    Warning: must be used in conjunction with EnhancedQuerySet, EnhancedManager,
    and EnhancedModel
    """
    def __init__(self, to, **kwargs):
        kwargs['null'] = True
        super(WeakForeignKey, self).__init__(to, **kwargs)



class CharField(models.CharField):
    """This is a CharField with a default max_length of 250.

       The arguments are also normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        if not kwargs.has_key('max_length'):
            kwargs['max_length'] = 250
        super(CharField, self).__init__(*args, **normalize_field(kwargs, ''))


class IntegerField(models.IntegerField):
    """IntegerField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(IntegerField, self).__init__(*args, **normalize_field(kwargs, 0))


class BooleanField(models.BooleanField):
    """BooleanField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(BooleanField, self).__init__(*args, **normalize_field(kwargs, False))


class TextField(models.TextField):
    """TextField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(TextField, self).__init__(*args, **normalize_field(kwargs, ''))


class DateTimeField(models.DateTimeField):
    """DateTimeField normalized with normalize_field(). This field is allowed to
    be null by default unless null=False is passed"""

    def __init__(self, *args, **kwargs):
        if not kwargs.has_key('null'):
            kwargs['null'] = True
        super(DateTimeField, self).__init__(*args, **normalize_field(kwargs))


class FileField(models.FileField):
    """FileField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(FileField, self).__init__(*args, **normalize_field(kwargs, ''))


class FloatField(models.FloatField):
    """FloatField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(FloatField, self).__init__(*args, **normalize_field(kwargs, 0))


class DateField(models.DateField):
    """DateField normalized with normalize_field(). This field is allowed to
    be null by default unless null=False is passed"""

    def __init__(self, *args, **kwargs):
        if not kwargs.has_key('null'):
            kwargs['null'] = True
        super(DateField, self).__init__(*args, **normalize_field(kwargs))


class RequiredFieldError(Exception):
    def __init__(self, model, field):
        self.model = model
        self.field = field
        super(Exception, self).__init__('%s.%s is required' % (model._meta.object_name, field.name))



# South introspection rules
add_introspection_rules([], ["^telemeta\.models\.fields\.CharField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.TextField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.FileField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.IntegerField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.BooleanField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.DateTimeField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.DateField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.FloatField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.DurationField"])
add_introspection_rules([], ["^telemeta\.models\.fields\.ForeignKey"])
add_introspection_rules([], ["^telemeta\.models\.fields\.WeakForeignKey"])

Classes

class BooleanField

BooleanField normalized with normalize_field()

class BooleanField(models.BooleanField):
    """BooleanField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(BooleanField, self).__init__(*args, **normalize_field(kwargs, False))

Ancestors (in MRO)

  • BooleanField
  • django.db.models.fields.BooleanField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    super(BooleanField, self).__init__(*args, **normalize_field(kwargs, False))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name, virtual_only=False)

def contribute_to_class(self, cls, name, virtual_only=False):
    self.set_attributes_from_name(name)
    self.model = cls
    if virtual_only:
        cls._meta.add_virtual_field(self)
    else:
        cls._meta.add_field(self)
    if self.choices:
        setattr(cls, 'get_%s_display' % self.name,
                curry(cls._get_FIELD_display, field=self))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    # Unlike most fields, BooleanField figures out include_blank from
    # self.null instead of self.blank.
    if self.choices:
        include_blank = (self.null or
                         not (self.has_default() or 'initial' in kwargs))
        defaults = {'choices': self.get_choices(
                                   include_blank=include_blank)}
    else:
        defaults = {'form_class': forms.BooleanField}
    defaults.update(kwargs)
    return super(BooleanField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "BooleanField"

def get_prep_lookup(

self, lookup_type, value)

def get_prep_lookup(self, lookup_type, value):
    # Special-case handling for filters coming from a Web request (e.g. the
    # admin interface). Only works for scalar values (not lists). If you're
    # passing in a list, you might as well make things the right type when
    # constructing the list.
    if value in ('1', '0'):
        value = bool(int(value))
    return super(BooleanField, self).get_prep_lookup(lookup_type, value)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    if value is None:
        return None
    return bool(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

def to_python(self, value):
    if value in (True, False):
        # if value is 1 or 0 than it's equal to True or False, but we want
        # to return a true bool for semantic reasons.
        return bool(value)
    if value in ('t', 'True', '1'):
        return True
    if value in ('f', 'False', '0'):
        return False
    raise exceptions.ValidationError(
        self.error_messages['invalid'],
        code='invalid',
        params={'value': value},
    )

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

Returns a string value of this field from the passed obj. This is used by the serialization framework.

def value_to_string(self, obj):
    """
    Returns a string value of this field from the passed obj.
    This is used by the serialization framework.
    """
    return smart_text(self._get_val_from_obj(obj))

class CharField

This is a CharField with a default max_length of 250.

The arguments are also normalized with normalize_field()

class CharField(models.CharField):
    """This is a CharField with a default max_length of 250.

       The arguments are also normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        if not kwargs.has_key('max_length'):
            kwargs['max_length'] = 250
        super(CharField, self).__init__(*args, **normalize_field(kwargs, ''))

Ancestors (in MRO)

  • CharField
  • django.db.models.fields.CharField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    if not kwargs.has_key('max_length'):
        kwargs['max_length'] = 250
    super(CharField, self).__init__(*args, **normalize_field(kwargs, ''))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name, virtual_only=False)

def contribute_to_class(self, cls, name, virtual_only=False):
    self.set_attributes_from_name(name)
    self.model = cls
    if virtual_only:
        cls._meta.add_virtual_field(self)
    else:
        cls._meta.add_field(self)
    if self.choices:
        setattr(cls, 'get_%s_display' % self.name,
                curry(cls._get_FIELD_display, field=self))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    # Passing max_length to forms.CharField means that the value's length
    # will be validated twice. This is considered acceptable since we want
    # the value in the form field (to pass into widget for example).
    defaults = {'max_length': self.max_length}
    defaults.update(kwargs)
    return super(CharField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "CharField"

def get_prep_lookup(

self, lookup_type, value)

Perform preliminary non-db specific lookup checks and conversions

def get_prep_lookup(self, lookup_type, value):
    """
    Perform preliminary non-db specific lookup checks and conversions
    """
    if hasattr(value, 'prepare'):
        return value.prepare()
    if hasattr(value, '_prepare'):
        return value._prepare()
    if lookup_type in (
            'iexact', 'contains', 'icontains',
            'startswith', 'istartswith', 'endswith', 'iendswith',
            'month', 'day', 'week_day', 'hour', 'minute', 'second',
            'isnull', 'search', 'regex', 'iregex',
        ):
        return value
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return self.get_prep_value(value)
    elif lookup_type in ('range', 'in'):
        return [self.get_prep_value(v) for v in value]
    elif lookup_type == 'year':
        try:
            return int(value)
        except ValueError:
            raise ValueError("The __year lookup type requires an integer "
                             "argument")
    raise TypeError("Field has invalid lookup: %s" % lookup_type)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    return self.to_python(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

def to_python(self, value):
    if isinstance(value, six.string_types) or value is None:
        return value
    return smart_text(value)

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

Returns a string value of this field from the passed obj. This is used by the serialization framework.

def value_to_string(self, obj):
    """
    Returns a string value of this field from the passed obj.
    This is used by the serialization framework.
    """
    return smart_text(self._get_val_from_obj(obj))

class DateField

DateField normalized with normalize_field(). This field is allowed to be null by default unless null=False is passed

class DateField(models.DateField):
    """DateField normalized with normalize_field(). This field is allowed to
    be null by default unless null=False is passed"""

    def __init__(self, *args, **kwargs):
        if not kwargs.has_key('null'):
            kwargs['null'] = True
        super(DateField, self).__init__(*args, **normalize_field(kwargs))

Ancestors (in MRO)

  • DateField
  • django.db.models.fields.DateField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    if not kwargs.has_key('null'):
        kwargs['null'] = True
    super(DateField, self).__init__(*args, **normalize_field(kwargs))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name)

def contribute_to_class(self, cls, name):
    super(DateField,self).contribute_to_class(cls, name)
    if not self.null:
        setattr(cls, 'get_next_by_%s' % self.name,
            curry(cls._get_next_or_previous_by_FIELD, field=self,
                  is_next=True))
        setattr(cls, 'get_previous_by_%s' % self.name,
            curry(cls._get_next_or_previous_by_FIELD, field=self,
                  is_next=False))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    defaults = {'form_class': forms.DateField}
    defaults.update(kwargs)
    return super(DateField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

def get_db_prep_value(self, value, connection, prepared=False):
    # Casts dates into the format expected by the backend
    if not prepared:
        value = self.get_prep_value(value)
    return connection.ops.value_to_db_date(value)

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "DateField"

def get_prep_lookup(

self, lookup_type, value)

def get_prep_lookup(self, lookup_type, value):
    # For dates lookups, convert the value to an int
    # so the database backend always sees a consistent type.
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute', 'second'):
        return int(value)
    return super(DateField, self).get_prep_lookup(lookup_type, value)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    return self.to_python(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

def pre_save(self, model_instance, add):
    if self.auto_now or (self.auto_now_add and add):
        value = datetime.date.today()
        setattr(model_instance, self.attname, value)
        return value
    else:
        return super(DateField, self).pre_save(model_instance, add)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

def to_python(self, value):
    if value is None:
        return value
    if isinstance(value, datetime.datetime):
        if settings.USE_TZ and timezone.is_aware(value):
            # Convert aware datetimes to the default time zone
            # before casting them to dates (#17742).
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_naive(value, default_timezone)
        return value.date()
    if isinstance(value, datetime.date):
        return value
    try:
        parsed = parse_date(value)
        if parsed is not None:
            return parsed
    except ValueError:
        raise exceptions.ValidationError(
            self.error_messages['invalid_date'],
            code='invalid_date',
            params={'value': value},
        )
    raise exceptions.ValidationError(
        self.error_messages['invalid'],
        code='invalid',
        params={'value': value},
    )

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

def value_to_string(self, obj):
    val = self._get_val_from_obj(obj)
    return '' if val is None else val.isoformat()

class DateTimeField

DateTimeField normalized with normalize_field(). This field is allowed to be null by default unless null=False is passed

class DateTimeField(models.DateTimeField):
    """DateTimeField normalized with normalize_field(). This field is allowed to
    be null by default unless null=False is passed"""

    def __init__(self, *args, **kwargs):
        if not kwargs.has_key('null'):
            kwargs['null'] = True
        super(DateTimeField, self).__init__(*args, **normalize_field(kwargs))

Ancestors (in MRO)

  • DateTimeField
  • django.db.models.fields.DateTimeField
  • django.db.models.fields.DateField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    if not kwargs.has_key('null'):
        kwargs['null'] = True
    super(DateTimeField, self).__init__(*args, **normalize_field(kwargs))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name)

def contribute_to_class(self, cls, name):
    super(DateField,self).contribute_to_class(cls, name)
    if not self.null:
        setattr(cls, 'get_next_by_%s' % self.name,
            curry(cls._get_next_or_previous_by_FIELD, field=self,
                  is_next=True))
        setattr(cls, 'get_previous_by_%s' % self.name,
            curry(cls._get_next_or_previous_by_FIELD, field=self,
                  is_next=False))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    defaults = {'form_class': forms.DateTimeField}
    defaults.update(kwargs)
    return super(DateTimeField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

def get_db_prep_value(self, value, connection, prepared=False):
    # Casts datetimes into the format expected by the backend
    if not prepared:
        value = self.get_prep_value(value)
    return connection.ops.value_to_db_datetime(value)

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "DateTimeField"

def get_prep_lookup(

self, lookup_type, value)

def get_prep_lookup(self, lookup_type, value):
    # For dates lookups, convert the value to an int
    # so the database backend always sees a consistent type.
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute', 'second'):
        return int(value)
    return super(DateField, self).get_prep_lookup(lookup_type, value)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    value = self.to_python(value)
    if value is not None and settings.USE_TZ and timezone.is_naive(value):
        # For backwards compatibility, interpret naive datetimes in local
        # time. This won't work during DST change, but we can't do much
        # about it, so we let the exceptions percolate up the call stack.
        warnings.warn("DateTimeField %s.%s received a naive datetime (%s)"
                      " while time zone support is active." %
                      (self.model.__name__, self.name, value),
                      RuntimeWarning)
        default_timezone = timezone.get_default_timezone()
        value = timezone.make_aware(value, default_timezone)
    return value

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

def pre_save(self, model_instance, add):
    if self.auto_now or (self.auto_now_add and add):
        value = timezone.now()
        setattr(model_instance, self.attname, value)
        return value
    else:
        return super(DateTimeField, self).pre_save(model_instance, add)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

def to_python(self, value):
    if value is None:
        return value
    if isinstance(value, datetime.datetime):
        return value
    if isinstance(value, datetime.date):
        value = datetime.datetime(value.year, value.month, value.day)
        if settings.USE_TZ:
            # For backwards compatibility, interpret naive datetimes in
            # local time. This won't work during DST change, but we can't
            # do much about it, so we let the exceptions percolate up the
            # call stack.
            warnings.warn("DateTimeField %s.%s received a naive datetime "
                          "(%s) while time zone support is active." %
                          (self.model.__name__, self.name, value),
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        return value
    try:
        parsed = parse_datetime(value)
        if parsed is not None:
            return parsed
    except ValueError:
        raise exceptions.ValidationError(
            self.error_messages['invalid_datetime'],
            code='invalid_datetime',
            params={'value': value},
        )
    try:
        parsed = parse_date(value)
        if parsed is not None:
            return datetime.datetime(parsed.year, parsed.month, parsed.day)
    except ValueError:
        raise exceptions.ValidationError(
            self.error_messages['invalid_date'],
            code='invalid_date',
            params={'value': value},
        )
    raise exceptions.ValidationError(
        self.error_messages['invalid'],
        code='invalid',
        params={'value': value},
    )

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

def value_to_string(self, obj):
    val = self._get_val_from_obj(obj)
    return '' if val is None else val.isoformat()

class Duration

Represent a time duration

class Duration(object):
    """Represent a time duration"""
    def __init__(self, *args, **kwargs):
        if len(args) and isinstance(args[0], datetime.timedelta):
            self._delta = datetime.timedelta(days=args[0].days, seconds=args[0].seconds)
        else:
            self._delta = datetime.timedelta(*args, **kwargs)

    def __decorate(self, method, other):
        if isinstance(other, Duration):
            res = method(other._delta)
        else:
            res = method(other)
        if type(res) == datetime.timedelta:
            return Duration(res)

        return res

    def __add__(self, other):
        return self.__decorate(self._delta.__add__, other)

    def __nonzero__(self):
        return self._delta.__nonzero__()

    def __str__(self):
        hours   = self._delta.days * 24 + self._delta.seconds / 3600
        minutes = (self._delta.seconds % 3600) / 60
        seconds = self._delta.seconds % 60

        return "%.2d:%.2d:%.2d" % (hours, minutes, seconds)

    def __unicode__(self):
        return self.__str__()

    @staticmethod
    def fromstr(str):
        if not str:
            return Duration()

        test = re.match('^([0-9]+)(?::([0-9]+)(?::([0-9]+))?)?$', str)
        if test:
            groups = test.groups()
            try:
                hours = minutes = seconds = 0
                if groups[0]:
                    hours = int(groups[0])
                    if groups[1]:
                        minutes = int(groups[1])
                        if groups[2]:
                            seconds = int(groups[2])

                return Duration(hours=hours, minutes=minutes, seconds=seconds)
            except TypeError:
                print groups
                raise
        else:
            raise ValueError("Malformed duration string: " + str)

    def as_seconds(self):
        return self._delta.days * 24 * 3600 + self._delta.seconds

Ancestors (in MRO)

Static methods

def fromstr(

str)

@staticmethod
def fromstr(str):
    if not str:
        return Duration()
    test = re.match('^([0-9]+)(?::([0-9]+)(?::([0-9]+))?)?$', str)
    if test:
        groups = test.groups()
        try:
            hours = minutes = seconds = 0
            if groups[0]:
                hours = int(groups[0])
                if groups[1]:
                    minutes = int(groups[1])
                    if groups[2]:
                        seconds = int(groups[2])
            return Duration(hours=hours, minutes=minutes, seconds=seconds)
        except TypeError:
            print groups
            raise
    else:
        raise ValueError("Malformed duration string: " + str)

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    if len(args) and isinstance(args[0], datetime.timedelta):
        self._delta = datetime.timedelta(days=args[0].days, seconds=args[0].seconds)
    else:
        self._delta = datetime.timedelta(*args, **kwargs)

def as_seconds(

self)

def as_seconds(self):
    return self._delta.days * 24 * 3600 + self._delta.seconds

class DurationField

Duration Django model field based on Django TimeField. Essentially the same as a TimeField, but with values over 24h allowed.

The constructor arguments are also normalized with normalize_field().

class DurationField(models.Field):
    """Duration Django model field based on Django TimeField.
    Essentially the same as a TimeField, but with values over 24h allowed.

    The constructor arguments are also normalized with normalize_field().
    """

    description = _("Duration")

    __metaclass__ = models.SubfieldBase

    default_error_messages = {
        'invalid': _('Enter a valid duration in HH:MM[:ss] format.'),
    }

    def __init__(self, *args, **kwargs):
        super(DurationField, self).__init__(*args, **normalize_field(kwargs, '0'))

    def db_type(self, connection):
        return 'int'

    def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, int) or isinstance(value, long):
            return Duration(seconds=value)
        if isinstance(value, datetime.time):
            return Duration(hours=value.hour, minutes=value.minute, seconds=value.second)
        if isinstance(value, datetime.datetime):
            # Not usually a good idea to pass in a datetime here (it loses
            # information), but this can be a side-effect of interacting with a
            # database backend (e.g. Oracle), so we'll be accommodating.
            return self.to_python(value.time())
        else:
            value = str(value)
        try:
            return Duration.fromstr(value)
        except ValueError:
            raise exceptions.ValidationError(self.error_messages['invalid'])

    def get_prep_value(self, value):
        return self.to_python(value)

    def get_db_prep_value(self, value, connection=None, prepared=False):
        # Casts times into the format expected by the backend
        try:
            return value.as_seconds()
        except:
            return value

    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        if val is None:
            data = ''
        else:
            data = unicode(val)
        return data

    def formfield(self, **kwargs):
        defaults = {'form_class': forms.CharField}
        defaults.update(kwargs)
        return super(DurationField, self).formfield(**defaults)

Ancestors (in MRO)

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    super(DurationField, self).__init__(*args, **normalize_field(kwargs, '0'))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name)

def contribute_to_class(self, cls, name):
    if func:
        func(self, cls, name)
    else:
        super(superclass, self).contribute_to_class(cls, name)
    setattr(cls, self.name, Creator(self))

def db_type(

self, connection)

def db_type(self, connection):
    return 'int'

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    defaults = {'form_class': forms.CharField}
    defaults.update(kwargs)
    return super(DurationField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection=None, prepared=False)

def get_db_prep_value(self, value, connection=None, prepared=False):
    # Casts times into the format expected by the backend
    try:
        return value.as_seconds()
    except:
        return value

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return self.__class__.__name__

def get_prep_lookup(

self, lookup_type, value)

Perform preliminary non-db specific lookup checks and conversions

def get_prep_lookup(self, lookup_type, value):
    """
    Perform preliminary non-db specific lookup checks and conversions
    """
    if hasattr(value, 'prepare'):
        return value.prepare()
    if hasattr(value, '_prepare'):
        return value._prepare()
    if lookup_type in (
            'iexact', 'contains', 'icontains',
            'startswith', 'istartswith', 'endswith', 'iendswith',
            'month', 'day', 'week_day', 'hour', 'minute', 'second',
            'isnull', 'search', 'regex', 'iregex',
        ):
        return value
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return self.get_prep_value(value)
    elif lookup_type in ('range', 'in'):
        return [self.get_prep_value(v) for v in value]
    elif lookup_type == 'year':
        try:
            return int(value)
        except ValueError:
            raise ValueError("The __year lookup type requires an integer "
                             "argument")
    raise TypeError("Field has invalid lookup: %s" % lookup_type)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    return self.to_python(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

def to_python(self, value):
    if value is None:
        return None
    if isinstance(value, int) or isinstance(value, long):
        return Duration(seconds=value)
    if isinstance(value, datetime.time):
        return Duration(hours=value.hour, minutes=value.minute, seconds=value.second)
    if isinstance(value, datetime.datetime):
        # Not usually a good idea to pass in a datetime here (it loses
        # information), but this can be a side-effect of interacting with a
        # database backend (e.g. Oracle), so we'll be accommodating.
        return self.to_python(value.time())
    else:
        value = str(value)
    try:
        return Duration.fromstr(value)
    except ValueError:
        raise exceptions.ValidationError(self.error_messages['invalid'])

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

def value_to_string(self, obj):
    val = self._get_val_from_obj(obj)
    if val is None:
        data = ''
    else:
        data = unicode(val)
    return data

class FileField

FileField normalized with normalize_field()

class FileField(models.FileField):
    """FileField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(FileField, self).__init__(*args, **normalize_field(kwargs, ''))

Ancestors (in MRO)

  • FileField
  • django.db.models.fields.files.FileField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var attr_class

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var descriptor_class

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    super(FileField, self).__init__(*args, **normalize_field(kwargs, ''))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name)

def contribute_to_class(self, cls, name):
    super(FileField, self).contribute_to_class(cls, name)
    setattr(cls, self.name, self.descriptor_class(self))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
    # If a file has been provided previously, then the form doesn't require
    # that a new file is provided this time.
    # The code to mark the form field as not required is used by
    # form_for_instance, but can probably be removed once form_for_instance
    # is gone. ModelForm uses a different method to check for an existing file.
    if 'initial' in kwargs:
        defaults['required'] = False
    defaults.update(kwargs)
    return super(FileField, self).formfield(**defaults)

def generate_filename(

self, instance, filename)

def generate_filename(self, instance, filename):
    return os.path.join(self.get_directory_name(), self.get_filename(filename))

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_directory_name(

self)

def get_directory_name(self):
    return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))

def get_filename(

self, filename)

def get_filename(self, filename):
    return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "FileField"

def get_prep_lookup(

self, lookup_type, value)

def get_prep_lookup(self, lookup_type, value):
    if hasattr(value, 'name'):
        value = value.name
    return super(FileField, self).get_prep_lookup(lookup_type, value)

def get_prep_value(

self, value)

Returns field's value prepared for saving into a database.

def get_prep_value(self, value):
    "Returns field's value prepared for saving into a database."
    # Need to convert File objects provided via a form to unicode for database insertion
    if value is None:
        return None
    return six.text_type(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    "Returns field's value just before saving."
    file = super(FileField, self).pre_save(model_instance, add)
    if file and not file._committed:
        # Commit the file to storage prior to saving the model
        file.save(file.name, file, save=False)
    return file

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    # Important: None means "no change", other false value means "clear"
    # This subtle distinction (rather than a more explicit marker) is
    # needed because we need to consume values that are also sane for a
    # regular (non Model-) Form to find in its cleaned_data dictionary.
    if data is not None:
        # This value will be converted to unicode and stored in the
        # database, so leaving False as-is is not acceptable.
        if not data:
            data = ''
        setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this.

def to_python(self, value):
    """
    Converts the input value into the expected Python data type, raising
    django.core.exceptions.ValidationError if the data can't be converted.
    Returns the converted value. Subclasses should override this.
    """
    return value

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

Returns a string value of this field from the passed obj. This is used by the serialization framework.

def value_to_string(self, obj):
    """
    Returns a string value of this field from the passed obj.
    This is used by the serialization framework.
    """
    return smart_text(self._get_val_from_obj(obj))

class FloatField

FloatField normalized with normalize_field()

class FloatField(models.FloatField):
    """FloatField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(FloatField, self).__init__(*args, **normalize_field(kwargs, 0))

Ancestors (in MRO)

  • FloatField
  • django.db.models.fields.FloatField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    super(FloatField, self).__init__(*args, **normalize_field(kwargs, 0))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name, virtual_only=False)

def contribute_to_class(self, cls, name, virtual_only=False):
    self.set_attributes_from_name(name)
    self.model = cls
    if virtual_only:
        cls._meta.add_virtual_field(self)
    else:
        cls._meta.add_field(self)
    if self.choices:
        setattr(cls, 'get_%s_display' % self.name,
                curry(cls._get_FIELD_display, field=self))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    defaults = {'form_class': forms.FloatField}
    defaults.update(kwargs)
    return super(FloatField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "FloatField"

def get_prep_lookup(

self, lookup_type, value)

Perform preliminary non-db specific lookup checks and conversions

def get_prep_lookup(self, lookup_type, value):
    """
    Perform preliminary non-db specific lookup checks and conversions
    """
    if hasattr(value, 'prepare'):
        return value.prepare()
    if hasattr(value, '_prepare'):
        return value._prepare()
    if lookup_type in (
            'iexact', 'contains', 'icontains',
            'startswith', 'istartswith', 'endswith', 'iendswith',
            'month', 'day', 'week_day', 'hour', 'minute', 'second',
            'isnull', 'search', 'regex', 'iregex',
        ):
        return value
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return self.get_prep_value(value)
    elif lookup_type in ('range', 'in'):
        return [self.get_prep_value(v) for v in value]
    elif lookup_type == 'year':
        try:
            return int(value)
        except ValueError:
            raise ValueError("The __year lookup type requires an integer "
                             "argument")
    raise TypeError("Field has invalid lookup: %s" % lookup_type)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    if value is None:
        return None
    return float(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

def to_python(self, value):
    if value is None:
        return value
    try:
        return float(value)
    except (TypeError, ValueError):
        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        )

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

Returns a string value of this field from the passed obj. This is used by the serialization framework.

def value_to_string(self, obj):
    """
    Returns a string value of this field from the passed obj.
    This is used by the serialization framework.
    """
    return smart_text(self._get_val_from_obj(obj))

class ForeignKey

The constructor arguments of this ForeignKey are normalized with normalize_field(), however the field is marked required by default unless it is allowed to be null.

class ForeignKey(models.ForeignKey):
    """The constructor arguments of this ForeignKey are normalized
    with normalize_field(), however the field is marked required by default
    unless it is allowed to be null."""

    def __init__(self, to, **kwargs):
        if not kwargs.has_key('required'):
            if not kwargs.get('null'):
                kwargs['required'] = True

        super(ForeignKey, self).__init__(to, **normalize_field(kwargs, 0))

Ancestors (in MRO)

  • ForeignKey
  • django.db.models.fields.related.ForeignKey
  • django.db.models.fields.related.ForeignObject
  • django.db.models.fields.related.RelatedField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

var generate_reverse_relation

var requires_unique_target

Static methods

def get_instance_value_for_fields(

instance, fields)

@staticmethod
def get_instance_value_for_fields(instance, fields):
    ret = []
    for field in fields:
        # Gotcha: in some cases (like fixture loading) a model can have
        # different values in parent_ptr_id and parent's id. So, use
        # instance.pk (that is, parent_ptr_id) when asked for instance.id.
        if field.primary_key:
            ret.append(instance.pk)
        else:
            ret.append(getattr(instance, field.attname))
    return tuple(ret)

Instance variables

var attnames

var choices

var flatchoices

Flattened version of choices tuple.

var related_field

var related_fields

var unique

Methods

def __init__(

self, to, **kwargs)

def __init__(self, to, **kwargs):
    if not kwargs.has_key('required'):
        if not kwargs.get('null'):
            kwargs['required'] = True
    super(ForeignKey, self).__init__(to, **normalize_field(kwargs, 0))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name, virtual_only=False)

def contribute_to_class(self, cls, name, virtual_only=False):
    super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
    setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self))

def db_type(

self, connection)

def db_type(self, connection):
    # The database column type of a ForeignKey is the column type
    # of the field to which it points. An exception is if the ForeignKey
    # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
    # in which case the column type is simply that of an IntegerField.
    # If the database needs similar types for key fields however, the only
    # thing we can do is making AutoField an IntegerField.
    rel_field = self.related_field
    if (isinstance(rel_field, AutoField) or
            (not connection.features.related_fields_match_type and
            isinstance(rel_field, (PositiveIntegerField,
                                   PositiveSmallIntegerField)))):
        return IntegerField().db_type(connection=connection)
    return rel_field.db_type(connection=connection)

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    db = kwargs.pop('using', None)
    if isinstance(self.rel.to, six.string_types):
        raise ValueError("Cannot create form field for %r yet, because "
                         "its related model %r has not been loaded yet" %
                         (self.name, self.rel.to))
    defaults = {
        'form_class': forms.ModelChoiceField,
        'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to),
        'to_field_name': self.rel.field_name,
    }
    defaults.update(kwargs)
    return super(ForeignKey, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return '%s_id' % self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

def get_db_prep_save(self, value, connection):
    if value == '' or value == None:
        return None
    else:
        return self.related_field.get_db_prep_save(value,
            connection=connection)

def get_db_prep_value(

self, value, connection, prepared=False)

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Here we check if the default value is an object and return the to_field if so.

def get_default(self):
    "Here we check if the default value is an object and return the to_field if so."
    field_default = super(ForeignKey, self).get_default()
    if isinstance(field_default, self.rel.to):
        return getattr(field_default, self.related_field.attname)
    return field_default

def get_defaults(

self)

def get_defaults(self):
    return tuple([field.get_default() for field in self.local_related_fields])

def get_extra_descriptor_filter(

self, instance)

Returns an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field.

The filter should be either a dict usable in .filter(**kwargs) call or a Q-object. The condition will be ANDed together with the relation's joining columns.

A parallel method is get_extra_restriction() which is used in JOIN and subquery conditions.

def get_extra_descriptor_filter(self, instance):
    """
    Returns an extra filter condition for related object fetching when
    user does 'instance.fieldname', that is the extra filter is used in
    the descriptor of the field.
    The filter should be either a dict usable in .filter(**kwargs) call or
    a Q-object. The condition will be ANDed together with the relation's
    joining columns.
    A parallel method is get_extra_restriction() which is used in
    JOIN and subquery conditions.
    """
    return {}

def get_extra_restriction(

self, where_class, alias, related_alias)

Returns a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(qn, connection) method.

Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown.

A parallel method is get_extra_descriptor_filter() which is used in instance.fieldname related object fetching.

def get_extra_restriction(self, where_class, alias, related_alias):
    """
    Returns a pair condition used for joining and subquery pushdown. The
    condition is something that responds to as_sql(qn, connection) method.
    Note that currently referring both the 'alias' and 'related_alias'
    will not work in some conditions, like subquery pushdown.
    A parallel method is get_extra_descriptor_filter() which is used in
    instance.fieldname related object fetching.
    """
    return None

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return self.__class__.__name__

def get_joining_columns(

self, reverse_join=False)

def get_joining_columns(self, reverse_join=False):
    source = self.reverse_related_fields if reverse_join else self.related_fields
    return tuple([(lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source])

def get_lookup_constraint(

self, constraint_class, alias, targets, sources, lookup_type, raw_value)

def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookup_type,
                          raw_value):
    from django.db.models.sql.where import SubqueryConstraint, Constraint, AND, OR
    root_constraint = constraint_class()
    assert len(targets) == len(sources)
    def get_normalized_value(value):
        from django.db.models import Model
        if isinstance(value, Model):
            value_list = []
            for source in sources:
                # Account for one-to-one relations when sent a different model
                while not isinstance(value, source.model) and source.rel:
                    source = source.rel.to._meta.get_field(source.rel.field_name)
                value_list.append(getattr(value, source.attname))
            return tuple(value_list)
        elif not isinstance(value, tuple):
            return (value,)
        return value
    is_multicolumn = len(self.related_fields) > 1
    if (hasattr(raw_value, '_as_sql') or
            hasattr(raw_value, 'get_compiler')):
        root_constraint.add(SubqueryConstraint(alias, [target.column for target in targets],
                                               [source.name for source in sources], raw_value),
                            AND)
    elif lookup_type == 'isnull':
        root_constraint.add(
            (Constraint(alias, targets[0].column, targets[0]), lookup_type, raw_value), AND)
    elif (lookup_type == 'exact' or (lookup_type in ['gt', 'lt', 'gte', 'lte']
                                     and not is_multicolumn)):
        value = get_normalized_value(raw_value)
        for index, source in enumerate(sources):
            root_constraint.add(
                (Constraint(alias, targets[index].column, sources[index]), lookup_type,
                 value[index]), AND)
    elif lookup_type in ['range', 'in'] and not is_multicolumn:
        values = [get_normalized_value(value) for value in raw_value]
        value = [val[0] for val in values]
        root_constraint.add(
            (Constraint(alias, targets[0].column, sources[0]), lookup_type, value), AND)
    elif lookup_type == 'in':
        values = [get_normalized_value(value) for value in raw_value]
        for value in values:
            value_constraint = constraint_class()
            for index, target in enumerate(targets):
                value_constraint.add(
                    (Constraint(alias, target.column, sources[index]), 'exact', value[index]),
                    AND)
            root_constraint.add(value_constraint, OR)
    else:
        raise TypeError('Related Field got invalid lookup: %s' % lookup_type)
    return root_constraint

def get_path_info(

self)

Get path from this field to the related model.

def get_path_info(self):
    """
    Get path from this field to the related model.
    """
    opts = self.rel.to._meta
    from_opts = self.model._meta
    return [PathInfo(from_opts, opts, self.foreign_related_fields, self, False, True)]

def get_prep_lookup(

self, lookup_type, value)

Perform preliminary non-db specific lookup checks and conversions

def get_prep_lookup(self, lookup_type, value):
    """
    Perform preliminary non-db specific lookup checks and conversions
    """
    if hasattr(value, 'prepare'):
        return value.prepare()
    if hasattr(value, '_prepare'):
        return value._prepare()
    if lookup_type in (
            'iexact', 'contains', 'icontains',
            'startswith', 'istartswith', 'endswith', 'iendswith',
            'month', 'day', 'week_day', 'hour', 'minute', 'second',
            'isnull', 'search', 'regex', 'iregex',
        ):
        return value
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return self.get_prep_value(value)
    elif lookup_type in ('range', 'in'):
        return [self.get_prep_value(v) for v in value]
    elif lookup_type == 'year':
        try:
            return int(value)
        except ValueError:
            raise ValueError("The __year lookup type requires an integer "
                             "argument")
    raise TypeError("Field has invalid lookup: %s" % lookup_type)

def get_prep_value(

self, value)

Perform preliminary non-db specific value checks and conversions.

def get_prep_value(self, value):
    """
    Perform preliminary non-db specific value checks and conversions.
    """
    return value

def get_reverse_joining_columns(

self)

def get_reverse_joining_columns(self):
    return self.get_joining_columns(reverse_join=True)

def get_reverse_path_info(

self)

Get path from the related model to this field's model.

def get_reverse_path_info(self):
    """
    Get path from the related model to this field's model.
    """
    opts = self.model._meta
    from_opts = self.rel.to._meta
    pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.rel, not self.unique, False)]
    return pathinfos

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__%s__exact' % (self.name, self.related_field.name)

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def related_query_name(

self)

def related_query_name(self):
    # This method defines the name that can be used to identify this
    # related object in a table-spanning query. It uses the lower-cased
    # object_name by default, but this can be overridden with the
    # "related_name" option.
    return self.rel.related_query_name or self.rel.related_name or self.opts.model_name

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def set_attributes_from_rel(

self)

def set_attributes_from_rel(self):
    self.name = self.name or (self.rel.to._meta.model_name + '_' + self.rel.to._meta.pk.name)
    if self.verbose_name is None:
        self.verbose_name = self.rel.to._meta.verbose_name
    self.rel.set_field_name()

def to_python(

self, value)

Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this.

def to_python(self, value):
    """
    Converts the input value into the expected Python data type, raising
    django.core.exceptions.ValidationError if the data can't be converted.
    Returns the converted value. Subclasses should override this.
    """
    return value

def validate(

self, value, model_instance)

def validate(self, value, model_instance):
    if self.rel.parent_link:
        return
    super(ForeignKey, self).validate(value, model_instance)
    if value is None:
        return
    using = router.db_for_read(model_instance.__class__, instance=model_instance)
    qs = self.rel.to._default_manager.using(using).filter(
            **{self.rel.field_name: value}
         )
    qs = qs.complex_filter(self.rel.limit_choices_to)
    if not qs.exists():
        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'model': self.rel.to._meta.verbose_name, 'pk': value},
        )

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

def value_to_string(self, obj):
    if not obj:
        # In required many-to-one fields with only one available choice,
        # select that one available choice. Note: For SelectFields
        # we have to check that the length of choices is *2*, not 1,
        # because SelectFields always have an initial "blank" value.
        if not self.blank and self.choices:
            choice_list = self.get_choices_default()
            if len(choice_list) == 2:
                return smart_text(choice_list[1][0])
    return super(ForeignKey, self).value_to_string(obj)

class IntegerField

IntegerField normalized with normalize_field()

class IntegerField(models.IntegerField):
    """IntegerField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(IntegerField, self).__init__(*args, **normalize_field(kwargs, 0))

Ancestors (in MRO)

  • IntegerField
  • django.db.models.fields.IntegerField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    super(IntegerField, self).__init__(*args, **normalize_field(kwargs, 0))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name, virtual_only=False)

def contribute_to_class(self, cls, name, virtual_only=False):
    self.set_attributes_from_name(name)
    self.model = cls
    if virtual_only:
        cls._meta.add_virtual_field(self)
    else:
        cls._meta.add_field(self)
    if self.choices:
        setattr(cls, 'get_%s_display' % self.name,
                curry(cls._get_FIELD_display, field=self))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    defaults = {'form_class': forms.IntegerField}
    defaults.update(kwargs)
    return super(IntegerField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "IntegerField"

def get_prep_lookup(

self, lookup_type, value)

def get_prep_lookup(self, lookup_type, value):
    if ((lookup_type == 'gte' or lookup_type == 'lt')
        and isinstance(value, float)):
        value = math.ceil(value)
    return super(IntegerField, self).get_prep_lookup(lookup_type, value)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    if value is None:
        return None
    return int(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

def to_python(self, value):
    if value is None:
        return value
    try:
        return int(value)
    except (TypeError, ValueError):
        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        )

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

Returns a string value of this field from the passed obj. This is used by the serialization framework.

def value_to_string(self, obj):
    """
    Returns a string value of this field from the passed obj.
    This is used by the serialization framework.
    """
    return smart_text(self._get_val_from_obj(obj))

class RequiredFieldError

class RequiredFieldError(Exception):
    def __init__(self, model, field):
        self.model = model
        self.field = field
        super(Exception, self).__init__('%s.%s is required' % (model._meta.object_name, field.name))

Ancestors (in MRO)

Class variables

var args

var message

Instance variables

var field

var model

Methods

def __init__(

self, model, field)

def __init__(self, model, field):
    self.model = model
    self.field = field
    super(Exception, self).__init__('%s.%s is required' % (model._meta.object_name, field.name))

class TextField

TextField normalized with normalize_field()

class TextField(models.TextField):
    """TextField normalized with normalize_field()"""

    def __init__(self, *args, **kwargs):
        super(TextField, self).__init__(*args, **normalize_field(kwargs, ''))

Ancestors (in MRO)

  • TextField
  • django.db.models.fields.TextField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

var creation_counter

var default_error_messages

var default_validators

var description

var empty_strings_allowed

var empty_values

Instance variables

var choices

var flatchoices

Flattened version of choices tuple.

var unique

Methods

def __init__(

self, *args, **kwargs)

def __init__(self, *args, **kwargs):
    super(TextField, self).__init__(*args, **normalize_field(kwargs, ''))

def bind(

self, fieldmapping, original, bound_field_class)

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name, virtual_only=False)

def contribute_to_class(self, cls, name, virtual_only=False):
    self.set_attributes_from_name(name)
    self.model = cls
    if virtual_only:
        cls._meta.add_virtual_field(self)
    else:
        cls._meta.add_field(self)
    if self.choices:
        setattr(cls, 'get_%s_display' % self.name,
                curry(cls._get_FIELD_display, field=self))

def db_type(

self, connection)

Returns the database column data type for this field, for the provided connection.

def db_type(self, connection):
    """
    Returns the database column data type for this field, for the provided
    connection.
    """
    # The default implementation of this method looks at the
    # backend-specific DATA_TYPES dictionary, looking up the field by its
    # "internal type".
    #
    # A Field class can implement the get_internal_type() method to specify
    # which *preexisting* Django Field class it's most similar to -- i.e.,
    # a custom field might be represented by a TEXT column type, which is
    # the same as the TextField Django field type, which means the custom
    # field's get_internal_type() returns 'TextField'.
    #
    # But the limitation of the get_internal_type() / data_types approach
    # is that it cannot handle database column types that aren't already
    # mapped to one of the built-in Django field types. In this case, you
    # can implement db_type() instead of get_internal_type() to specify
    # exactly which wacky database column type you want to use.
    data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
    try:
        return (connection.creation.data_types[self.get_internal_type()]
                % data)
    except KeyError:
        return None

def formfield(

self, **kwargs)

def formfield(self, **kwargs):
    defaults = {'widget': forms.Textarea}
    defaults.update(kwargs)
    return super(TextField, self).formfield(**defaults)

def get_attname(

self)

def get_attname(self):
    return self.name

def get_attname_column(

self)

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Returns field's value prepared for saving into a database.

def get_db_prep_save(self, value, connection):
    """
    Returns field's value prepared for saving into a database.
    """
    return self.get_db_prep_value(value, connection=connection,
                                  prepared=False)

def get_db_prep_value(

self, value, connection, prepared=False)

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Returns the default value for this field.

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

def get_internal_type(

self)

def get_internal_type(self):
    return "TextField"

def get_prep_lookup(

self, lookup_type, value)

Perform preliminary non-db specific lookup checks and conversions

def get_prep_lookup(self, lookup_type, value):
    """
    Perform preliminary non-db specific lookup checks and conversions
    """
    if hasattr(value, 'prepare'):
        return value.prepare()
    if hasattr(value, '_prepare'):
        return value._prepare()
    if lookup_type in (
            'iexact', 'contains', 'icontains',
            'startswith', 'istartswith', 'endswith', 'iendswith',
            'month', 'day', 'week_day', 'hour', 'minute', 'second',
            'isnull', 'search', 'regex', 'iregex',
        ):
        return value
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return self.get_prep_value(value)
    elif lookup_type in ('range', 'in'):
        return [self.get_prep_value(v) for v in value]
    elif lookup_type == 'year':
        try:
            return int(value)
        except ValueError:
            raise ValueError("The __year lookup type requires an integer "
                             "argument")
    raise TypeError("Field has invalid lookup: %s" % lookup_type)

def get_prep_value(

self, value)

def get_prep_value(self, value):
    if isinstance(value, six.string_types) or value is None:
        return value
    return smart_text(value)

def get_validator_unique_lookup_type(

self)

def get_validator_unique_lookup_type(self):
    return '%s__exact' % self.name

def has_default(

self)

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def run_validators(

self, value)

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def to_python(

self, value)

Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this.

def to_python(self, value):
    """
    Converts the input value into the expected Python data type, raising
    django.core.exceptions.ValidationError if the data can't be converted.
    Returns the converted value. Subclasses should override this.
    """
    return value

def validate(

self, value, model_instance)

Validates value and throws ValidationError. Subclasses should override this to provide validation logic.

def validate(self, value, model_instance):
    """
    Validates value and throws ValidationError. Subclasses should override
    this to provide validation logic.
    """
    if not self.editable:
        # Skip validation for non-editable fields.
        return
    if self._choices and value not in self.empty_values:
        for option_key, option_value in self.choices:
            if isinstance(option_value, (list, tuple)):
                # This is an optgroup, so look inside the group for
                # options.
                for optgroup_key, optgroup_value in option_value:
                    if value == optgroup_key:
                        return
            elif value == option_key:
                return
        raise exceptions.ValidationError(
            self.error_messages['invalid_choice'],
            code='invalid_choice',
            params={'value': value},
        )
    if value is None and not self.null:
        raise exceptions.ValidationError(self.error_messages['null'], code='null')
    if not self.blank and value in self.empty_values:
        raise exceptions.ValidationError(self.error_messages['blank'], code='blank')

def value_from_object(

self, obj)

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

Returns a string value of this field from the passed obj. This is used by the serialization framework.

def value_to_string(self, obj):
    """
    Returns a string value of this field from the passed obj.
    This is used by the serialization framework.
    """
    return smart_text(self._get_val_from_obj(obj))

class WeakForeignKey

A weak foreign key is the same as foreign key but without cascading delete. Instead the reference is set to null when the referenced record get deleted. This emulates the ON DELETE SET NULL sql behaviour.

This field is automatically allowed to be null, there's no need to pass null=True.

The constructor arguments are normalized with normalize_field() by the parent ForeignKey

Warning: must be used in conjunction with EnhancedQuerySet, EnhancedManager, and EnhancedModel

class WeakForeignKey(ForeignKey):
    """A weak foreign key is the same as foreign key but without cascading
    delete. Instead the reference is set to null when the referenced record
    get deleted. This emulates the ON DELETE SET NULL sql behaviour.

    This field is automatically allowed to be null, there's no need to pass
    null=True.

    The constructor arguments are normalized with normalize_field() by the
    parent ForeignKey

    Warning: must be used in conjunction with EnhancedQuerySet, EnhancedManager,
    and EnhancedModel
    """
    def __init__(self, to, **kwargs):
        kwargs['null'] = True
        super(WeakForeignKey, self).__init__(to, **kwargs)

Ancestors (in MRO)

  • WeakForeignKey
  • ForeignKey
  • django.db.models.fields.related.ForeignKey
  • django.db.models.fields.related.ForeignObject
  • django.db.models.fields.related.RelatedField
  • django.db.models.fields.Field
  • __builtin__.object

Class variables

var auto_creation_counter

Inheritance: ForeignKey.auto_creation_counter

var creation_counter

Inheritance: ForeignKey.creation_counter

var default_error_messages

Inheritance: ForeignKey.default_error_messages

var default_validators

Inheritance: ForeignKey.default_validators

var description

Inheritance: ForeignKey.description

var empty_strings_allowed

Inheritance: ForeignKey.empty_strings_allowed

var empty_values

Inheritance: ForeignKey.empty_values

var generate_reverse_relation

Inheritance: ForeignKey.generate_reverse_relation

var requires_unique_target

Inheritance: ForeignKey.requires_unique_target

Static methods

def get_instance_value_for_fields(

instance, fields)

Inheritance: ForeignKey.get_instance_value_for_fields

@staticmethod
def get_instance_value_for_fields(instance, fields):
    ret = []
    for field in fields:
        # Gotcha: in some cases (like fixture loading) a model can have
        # different values in parent_ptr_id and parent's id. So, use
        # instance.pk (that is, parent_ptr_id) when asked for instance.id.
        if field.primary_key:
            ret.append(instance.pk)
        else:
            ret.append(getattr(instance, field.attname))
    return tuple(ret)

Instance variables

var attnames

Inheritance: ForeignKey.attnames

var choices

Inheritance: ForeignKey.choices

var flatchoices

Inheritance: ForeignKey.flatchoices

Flattened version of choices tuple.

Inheritance: ForeignKey.foreign_related_fields

Inheritance: ForeignKey.local_related_fields

var related_field

Inheritance: ForeignKey.related_field

var related_fields

Inheritance: ForeignKey.related_fields

Inheritance: ForeignKey.reverse_related_fields

var unique

Inheritance: ForeignKey.unique

Methods

def __init__(

self, to, **kwargs)

Inheritance: ForeignKey.__init__

def __init__(self, to, **kwargs):
    kwargs['null'] = True
    super(WeakForeignKey, self).__init__(to, **kwargs)

def bind(

self, fieldmapping, original, bound_field_class)

Inheritance: ForeignKey.bind

def bind(self, fieldmapping, original, bound_field_class):
    return bound_field_class(self, fieldmapping, original)

def clean(

self, value, model_instance)

Inheritance: ForeignKey.clean

Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.

def clean(self, value, model_instance):
    """
    Convert the value's type and run validation. Validation errors
    from to_python and validate are propagated. The correct value is
    returned if no error is raised.
    """
    value = self.to_python(value)
    self.validate(value, model_instance)
    self.run_validators(value)
    return value

def contribute_to_class(

self, cls, name, virtual_only=False)

Inheritance: ForeignKey.contribute_to_class

def contribute_to_class(self, cls, name, virtual_only=False):
    super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
    setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self))

Inheritance: ForeignKey.contribute_to_related_class

def db_type(

self, connection)

Inheritance: ForeignKey.db_type

def db_type(self, connection):
    # The database column type of a ForeignKey is the column type
    # of the field to which it points. An exception is if the ForeignKey
    # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
    # in which case the column type is simply that of an IntegerField.
    # If the database needs similar types for key fields however, the only
    # thing we can do is making AutoField an IntegerField.
    rel_field = self.related_field
    if (isinstance(rel_field, AutoField) or
            (not connection.features.related_fields_match_type and
            isinstance(rel_field, (PositiveIntegerField,
                                   PositiveSmallIntegerField)))):
        return IntegerField().db_type(connection=connection)
    return rel_field.db_type(connection=connection)

Inheritance: ForeignKey.do_related_class

def formfield(

self, **kwargs)

Inheritance: ForeignKey.formfield

def formfield(self, **kwargs):
    db = kwargs.pop('using', None)
    if isinstance(self.rel.to, six.string_types):
        raise ValueError("Cannot create form field for %r yet, because "
                         "its related model %r has not been loaded yet" %
                         (self.name, self.rel.to))
    defaults = {
        'form_class': forms.ModelChoiceField,
        'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to),
        'to_field_name': self.rel.field_name,
    }
    defaults.update(kwargs)
    return super(ForeignKey, self).formfield(**defaults)

def get_attname(

self)

Inheritance: ForeignKey.get_attname

def get_attname(self):
    return '%s_id' % self.name

def get_attname_column(

self)

Inheritance: ForeignKey.get_attname_column

def get_attname_column(self):
    attname = self.get_attname()
    column = self.db_column or attname
    return attname, column

def get_cache_name(

self)

Inheritance: ForeignKey.get_cache_name

def get_cache_name(self):
    return '_%s_cache' % self.name

def get_choices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Inheritance: ForeignKey.get_choices

Returns choices with a default blank choices included, for use as SelectField choices for this field.

def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
    """Returns choices with a default blank choices included, for use
    as SelectField choices for this field."""
    first_choice = blank_choice if include_blank else []
    if self.choices:
        return first_choice + list(self.choices)
    rel_model = self.rel.to
    if hasattr(self.rel, 'get_related_field'):
        lst = [(getattr(x, self.rel.get_related_field().attname),
                    smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    else:
        lst = [(x._get_pk_val(), smart_text(x))
               for x in rel_model._default_manager.complex_filter(
                   self.rel.limit_choices_to)]
    return first_choice + lst

def get_choices_default(

self)

Inheritance: ForeignKey.get_choices_default

def get_choices_default(self):
    return self.get_choices()

def get_db_prep_lookup(

self, lookup_type, value, connection, prepared=False)

Inheritance: ForeignKey.get_db_prep_lookup

Returns field's value prepared for database lookup.

def get_db_prep_lookup(self, lookup_type, value, connection,
                       prepared=False):
    """
    Returns field's value prepared for database lookup.
    """
    if not prepared:
        value = self.get_prep_lookup(lookup_type, value)
        prepared = True
    if hasattr(value, 'get_compiler'):
        value = value.get_compiler(connection=connection)
    if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
        # If the value has a relabeled_clone method it means the
        # value will be handled later on.
        if hasattr(value, 'relabeled_clone'):
            return value
        if hasattr(value, 'as_sql'):
            sql, params = value.as_sql()
        else:
            sql, params = value._as_sql(connection=connection)
        return QueryWrapper(('(%s)' % sql), params)
    if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
                       'second', 'search', 'regex', 'iregex'):
        return [value]
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return [self.get_db_prep_value(value, connection=connection,
                                       prepared=prepared)]
    elif lookup_type in ('range', 'in'):
        return [self.get_db_prep_value(v, connection=connection,
                                       prepared=prepared) for v in value]
    elif lookup_type in ('contains', 'icontains'):
        return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'iexact':
        return [connection.ops.prep_for_iexact_query(value)]
    elif lookup_type in ('startswith', 'istartswith'):
        return ["%s%%" % connection.ops.prep_for_like_query(value)]
    elif lookup_type in ('endswith', 'iendswith'):
        return ["%%%s" % connection.ops.prep_for_like_query(value)]
    elif lookup_type == 'isnull':
        return []
    elif lookup_type == 'year':
        if isinstance(self, DateTimeField):
            return connection.ops.year_lookup_bounds_for_datetime_field(value)
        elif isinstance(self, DateField):
            return connection.ops.year_lookup_bounds_for_date_field(value)
        else:
            return [value]          # this isn't supposed to happen

def get_db_prep_save(

self, value, connection)

Inheritance: ForeignKey.get_db_prep_save

def get_db_prep_save(self, value, connection):
    if value == '' or value == None:
        return None
    else:
        return self.related_field.get_db_prep_save(value,
            connection=connection)

def get_db_prep_value(

self, value, connection, prepared=False)

Inheritance: ForeignKey.get_db_prep_value

Returns field's value prepared for interacting with the database backend.

Used by the default implementations of get_db_prep_saveand `get_db_prep_lookup```

def get_db_prep_value(self, value, connection, prepared=False):
    """Returns field's value prepared for interacting with the database
    backend.
    Used by the default implementations of ``get_db_prep_save``and
    `get_db_prep_lookup```
    """
    if not prepared:
        value = self.get_prep_value(value)
    return value

def get_default(

self)

Inheritance: ForeignKey.get_default

Here we check if the default value is an object and return the to_field if so.

def get_default(self):
    "Here we check if the default value is an object and return the to_field if so."
    field_default = super(ForeignKey, self).get_default()
    if isinstance(field_default, self.rel.to):
        return getattr(field_default, self.related_field.attname)
    return field_default

def get_defaults(

self)

Inheritance: ForeignKey.get_defaults

def get_defaults(self):
    return tuple([field.get_default() for field in self.local_related_fields])

def get_extra_descriptor_filter(

self, instance)

Inheritance: ForeignKey.get_extra_descriptor_filter

Returns an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field.

The filter should be either a dict usable in .filter(**kwargs) call or a Q-object. The condition will be ANDed together with the relation's joining columns.

A parallel method is get_extra_restriction() which is used in JOIN and subquery conditions.

def get_extra_descriptor_filter(self, instance):
    """
    Returns an extra filter condition for related object fetching when
    user does 'instance.fieldname', that is the extra filter is used in
    the descriptor of the field.
    The filter should be either a dict usable in .filter(**kwargs) call or
    a Q-object. The condition will be ANDed together with the relation's
    joining columns.
    A parallel method is get_extra_restriction() which is used in
    JOIN and subquery conditions.
    """
    return {}

def get_extra_restriction(

self, where_class, alias, related_alias)

Inheritance: ForeignKey.get_extra_restriction

Returns a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(qn, connection) method.

Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown.

A parallel method is get_extra_descriptor_filter() which is used in instance.fieldname related object fetching.

def get_extra_restriction(self, where_class, alias, related_alias):
    """
    Returns a pair condition used for joining and subquery pushdown. The
    condition is something that responds to as_sql(qn, connection) method.
    Note that currently referring both the 'alias' and 'related_alias'
    will not work in some conditions, like subquery pushdown.
    A parallel method is get_extra_descriptor_filter() which is used in
    instance.fieldname related object fetching.
    """
    return None

def get_flatchoices(

self, include_blank=True, blank_choice=[(u'', u'---------')])

Inheritance: ForeignKey.get_flatchoices

Returns flattened choices with a default blank choice included.

def get_flatchoices(self, include_blank=True,
                    blank_choice=BLANK_CHOICE_DASH):
    """
    Returns flattened choices with a default blank choice included.
    """
    first_choice = blank_choice if include_blank else []
    return first_choice + list(self.flatchoices)

Inheritance: ForeignKey.get_foreign_related_value

def get_internal_type(

self)

Inheritance: ForeignKey.get_internal_type

def get_internal_type(self):
    return self.__class__.__name__

def get_joining_columns(

self, reverse_join=False)

Inheritance: ForeignKey.get_joining_columns

def get_joining_columns(self, reverse_join=False):
    source = self.reverse_related_fields if reverse_join else self.related_fields
    return tuple([(lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source])

Inheritance: ForeignKey.get_local_related_value

def get_lookup_constraint(

self, constraint_class, alias, targets, sources, lookup_type, raw_value)

Inheritance: ForeignKey.get_lookup_constraint

def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookup_type,
                          raw_value):
    from django.db.models.sql.where import SubqueryConstraint, Constraint, AND, OR
    root_constraint = constraint_class()
    assert len(targets) == len(sources)
    def get_normalized_value(value):
        from django.db.models import Model
        if isinstance(value, Model):
            value_list = []
            for source in sources:
                # Account for one-to-one relations when sent a different model
                while not isinstance(value, source.model) and source.rel:
                    source = source.rel.to._meta.get_field(source.rel.field_name)
                value_list.append(getattr(value, source.attname))
            return tuple(value_list)
        elif not isinstance(value, tuple):
            return (value,)
        return value
    is_multicolumn = len(self.related_fields) > 1
    if (hasattr(raw_value, '_as_sql') or
            hasattr(raw_value, 'get_compiler')):
        root_constraint.add(SubqueryConstraint(alias, [target.column for target in targets],
                                               [source.name for source in sources], raw_value),
                            AND)
    elif lookup_type == 'isnull':
        root_constraint.add(
            (Constraint(alias, targets[0].column, targets[0]), lookup_type, raw_value), AND)
    elif (lookup_type == 'exact' or (lookup_type in ['gt', 'lt', 'gte', 'lte']
                                     and not is_multicolumn)):
        value = get_normalized_value(raw_value)
        for index, source in enumerate(sources):
            root_constraint.add(
                (Constraint(alias, targets[index].column, sources[index]), lookup_type,
                 value[index]), AND)
    elif lookup_type in ['range', 'in'] and not is_multicolumn:
        values = [get_normalized_value(value) for value in raw_value]
        value = [val[0] for val in values]
        root_constraint.add(
            (Constraint(alias, targets[0].column, sources[0]), lookup_type, value), AND)
    elif lookup_type == 'in':
        values = [get_normalized_value(value) for value in raw_value]
        for value in values:
            value_constraint = constraint_class()
            for index, target in enumerate(targets):
                value_constraint.add(
                    (Constraint(alias, target.column, sources[index]), 'exact', value[index]),
                    AND)
            root_constraint.add(value_constraint, OR)
    else:
        raise TypeError('Related Field got invalid lookup: %s' % lookup_type)
    return root_constraint

def get_path_info(

self)

Inheritance: ForeignKey.get_path_info

Get path from this field to the related model.

def get_path_info(self):
    """
    Get path from this field to the related model.
    """
    opts = self.rel.to._meta
    from_opts = self.model._meta
    return [PathInfo(from_opts, opts, self.foreign_related_fields, self, False, True)]

def get_prep_lookup(

self, lookup_type, value)

Inheritance: ForeignKey.get_prep_lookup

Perform preliminary non-db specific lookup checks and conversions

def get_prep_lookup(self, lookup_type, value):
    """
    Perform preliminary non-db specific lookup checks and conversions
    """
    if hasattr(value, 'prepare'):
        return value.prepare()
    if hasattr(value, '_prepare'):
        return value._prepare()
    if lookup_type in (
            'iexact', 'contains', 'icontains',
            'startswith', 'istartswith', 'endswith', 'iendswith',
            'month', 'day', 'week_day', 'hour', 'minute', 'second',
            'isnull', 'search', 'regex', 'iregex',
        ):
        return value
    elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
        return self.get_prep_value(value)
    elif lookup_type in ('range', 'in'):
        return [self.get_prep_value(v) for v in value]
    elif lookup_type == 'year':
        try:
            return int(value)
        except ValueError:
            raise ValueError("The __year lookup type requires an integer "
                             "argument")
    raise TypeError("Field has invalid lookup: %s" % lookup_type)

def get_prep_value(

self, value)

Inheritance: ForeignKey.get_prep_value

Perform preliminary non-db specific value checks and conversions.

def get_prep_value(self, value):
    """
    Perform preliminary non-db specific value checks and conversions.
    """
    return value

def get_reverse_joining_columns(

self)

Inheritance: ForeignKey.get_reverse_joining_columns

def get_reverse_joining_columns(self):
    return self.get_joining_columns(reverse_join=True)

def get_reverse_path_info(

self)

Inheritance: ForeignKey.get_reverse_path_info

Get path from the related model to this field's model.

def get_reverse_path_info(self):
    """
    Get path from the related model to this field's model.
    """
    opts = self.model._meta
    from_opts = self.rel.to._meta
    pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.rel, not self.unique, False)]
    return pathinfos

def get_validator_unique_lookup_type(

self)

Inheritance: ForeignKey.get_validator_unique_lookup_type

def get_validator_unique_lookup_type(self):
    return '%s__%s__exact' % (self.name, self.related_field.name)

def has_default(

self)

Inheritance: ForeignKey.has_default

Returns a boolean of whether this field has a default value.

def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def pre_save(

self, model_instance, add)

Inheritance: ForeignKey.pre_save

Returns field's value just before saving.

def pre_save(self, model_instance, add):
    """
    Returns field's value just before saving.
    """
    return getattr(model_instance, self.attname)

def related_query_name(

self)

Inheritance: ForeignKey.related_query_name

def related_query_name(self):
    # This method defines the name that can be used to identify this
    # related object in a table-spanning query. It uses the lower-cased
    # object_name by default, but this can be overridden with the
    # "related_name" option.
    return self.rel.related_query_name or self.rel.related_name or self.opts.model_name

Inheritance: ForeignKey.resolve_related_fields

def run_validators(

self, value)

Inheritance: ForeignKey.run_validators

def run_validators(self, value):
    if value in self.empty_values:
        return
    errors = []
    for v in self.validators:
        try:
            v(value)
        except exceptions.ValidationError as e:
            if hasattr(e, 'code') and e.code in self.error_messages:
                e.message = self.error_messages[e.code]
            errors.extend(e.error_list)
    if errors:
        raise exceptions.ValidationError(errors)

def save_form_data(

self, instance, data)

Inheritance: ForeignKey.save_form_data

def save_form_data(self, instance, data):
    setattr(instance, self.name, data)

def set_attributes_from_name(

self, name)

Inheritance: ForeignKey.set_attributes_from_name

def set_attributes_from_name(self, name):
    if not self.name:
        self.name = name
    self.attname, self.column = self.get_attname_column()
    if self.verbose_name is None and self.name:
        self.verbose_name = self.name.replace('_', ' ')

def set_attributes_from_rel(

self)

Inheritance: ForeignKey.set_attributes_from_rel

def set_attributes_from_rel(self):
    self.name = self.name or (self.rel.to._meta.model_name + '_' + self.rel.to._meta.pk.name)
    if self.verbose_name is None:
        self.verbose_name = self.rel.to._meta.verbose_name
    self.rel.set_field_name()

def to_python(

self, value)

Inheritance: ForeignKey.to_python

Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this.

def to_python(self, value):
    """
    Converts the input value into the expected Python data type, raising
    django.core.exceptions.ValidationError if the data can't be converted.
    Returns the converted value. Subclasses should override this.
    """
    return value

def validate(

self, value, model_instance)

Inheritance: ForeignKey.validate

def validate(self, value, model_instance):
    if self.rel.parent_link:
        return
    super(ForeignKey, self).validate(value, model_instance)
    if value is None:
        return
    using = router.db_for_read(model_instance.__class__, instance=model_instance)
    qs = self.rel.to._default_manager.using(using).filter(
            **{self.rel.field_name: value}
         )
    qs = qs.complex_filter(self.rel.limit_choices_to)
    if not qs.exists():
        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'model': self.rel.to._meta.verbose_name, 'pk': value},
        )

def value_from_object(

self, obj)

Inheritance: ForeignKey.value_from_object

Returns the value of this field in the given model instance.

def value_from_object(self, obj):
    """
    Returns the value of this field in the given model instance.
    """
    return getattr(obj, self.attname)

def value_to_string(

self, obj)

Inheritance: ForeignKey.value_to_string

def value_to_string(self, obj):
    if not obj:
        # In required many-to-one fields with only one available choice,
        # select that one available choice. Note: For SelectFields
        # we have to check that the length of choices is *2*, not 1,
        # because SelectFields always have an initial "blank" value.
        if not self.blank and self.choices:
            choice_list = self.get_choices_default()
            if len(choice_list) == 2:
                return smart_text(choice_list[1][0])
    return super(ForeignKey, self).value_to_string(obj)