Ticket #24042: patch.diff

File patch.diff, 11.9 KB (added by Lucas Wiman, 10 years ago)
  • django/db/backends/__init__.py

    diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py
    index 104744b..a3c4317 100644
    a b class BaseDatabaseIntrospection(object):  
    14001400    def sequence_list(self):
    14011401        "Returns a list of information about all DB sequences for all models in all apps."
    14021402        from django.apps import apps
    1403         from django.db import models, router
     1403        from django.db import router
    14041404
    14051405        sequence_list = []
    14061406
    class BaseDatabaseIntrospection(object):  
    14111411                if model._meta.swapped:
    14121412                    continue
    14131413                for f in model._meta.local_fields:
    1414                     if isinstance(f, models.AutoField):
     1414                    if f.get_internal_type() == 'AutoField':
    14151415                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
    14161416                        break  # Only one AutoField is allowed per model, so don't bother continuing.
    14171417
  • django/db/backends/oracle/base.py

    diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
    index 9f275b7..c7a162c 100644
    a b WHEN (new.%(col_name)s IS NULL)  
    444444        return sql
    445445
    446446    def sequence_reset_sql(self, style, model_list):
    447         from django.db import models
    448447        output = []
    449448        query = _get_sequence_reset_sql()
    450449        for model in model_list:
    451450            for f in model._meta.local_fields:
    452                 if isinstance(f, models.AutoField):
     451                if f.get_internal_type() == 'AutoField':
    453452                    table_name = self.quote_name(model._meta.db_table)
    454453                    sequence_name = self._get_sequence_name(model._meta.db_table)
    455454                    column_name = self.quote_name(f.column)
  • django/db/backends/postgresql_psycopg2/operations.py

    diff --git a/django/db/backends/postgresql_psycopg2/operations.py b/django/db/backends/postgresql_psycopg2/operations.py
    index 3447bfe..181d8c4 100644
    a b class DatabaseOperations(BaseDatabaseOperations):  
    135135            return "TABLESPACE %s" % self.quote_name(tablespace)
    136136
    137137    def sequence_reset_sql(self, style, model_list):
    138         from django.db import models
    139138        output = []
    140139        qn = self.quote_name
    141140        for model in model_list:
    class DatabaseOperations(BaseDatabaseOperations):  
    146145            # and column name (available since PostgreSQL 8)
    147146
    148147            for f in model._meta.local_fields:
    149                 if isinstance(f, models.AutoField):
     148                if f.get_internal_type() == 'AutoField':
    150149                    output.append(
    151150                        "%s setval(pg_get_serial_sequence('%s','%s'), "
    152151                        "coalesce(max(%s), 1), max(%s) %s null) %s %s;" % (
  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    index d0c1b7a..e68fb20 100644
    a b from django.db import (router, connections, transaction, DatabaseError,  
    1616from django.db.models import signals
    1717from django.db.models.constants import LOOKUP_SEP
    1818from django.db.models.deletion import Collector
    19 from django.db.models.fields import AutoField, FieldDoesNotExist
     19from django.db.models.fields import FieldDoesNotExist
    2020from django.db.models.fields.related import (ForeignObjectRel, ManyToOneRel,
    2121    OneToOneField, add_lazy_relation)
    2222from django.db.models.manager import ensure_default_manager
    class Model(six.with_metaclass(ModelBase)):  
    797797
    798798            fields = meta.local_concrete_fields
    799799            if not pk_set:
    800                 fields = [f for f in fields if not isinstance(f, AutoField)]
     800                fields = [f for f in fields if not f.get_internal_type() == "AutoField"]
    801801
    802802            update_pk = bool(meta.has_auto_field and not pk_set)
    803803            result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index a2f4b95..dc563fb 100644
    a b from django.db import connection, connections, router, transaction  
    88from django.db.backends import utils
    99from django.db.models import signals, Q
    1010from django.db.models.deletion import SET_NULL, SET_DEFAULT, CASCADE
    11 from django.db.models.fields import (AutoField, Field, IntegerField,
     11from django.db.models.fields import (Field, IntegerField,
    1212    PositiveIntegerField, PositiveSmallIntegerField, FieldDoesNotExist)
    1313from django.db.models.lookups import IsNull
    1414from django.db.models.related import RelatedObject, PathInfo
    class ForeignKey(ForeignObject):  
    18601860        # If the database needs similar types for key fields however, the only
    18611861        # thing we can do is making AutoField an IntegerField.
    18621862        rel_field = self.related_field
    1863         if (isinstance(rel_field, AutoField) or
     1863        if (rel_field.get_internal_type() == 'AutoField' or
    18641864                (not connection.features.related_fields_match_type and
    18651865                isinstance(rel_field, (PositiveIntegerField,
    18661866                                       PositiveSmallIntegerField)))):
  • django/db/models/query.py

    diff --git a/django/db/models/query.py b/django/db/models/query.py
    index 42dfd47..b17a8fc 100644
    a b from django.core import exceptions  
    1212from django.db import (connections, router, transaction, IntegrityError,
    1313    DJANGO_VERSION_PICKLE_KEY)
    1414from django.db.models.constants import LOOKUP_SEP
    15 from django.db.models.fields import AutoField, Empty
     15from django.db.models.fields import Empty
    1616from django.db.models.query_utils import (Q, select_related_descend,
    1717    deferred_class_factory, InvalidQuery)
    1818from django.db.models.deletion import Collector
    class QuerySet(object):  
    424424                if objs_with_pk:
    425425                    self._batched_insert(objs_with_pk, fields, batch_size)
    426426                if objs_without_pk:
    427                     fields = [f for f in fields if not isinstance(f, AutoField)]
     427                    fields = [f for f in fields if not f.get_internal_type() == 'AutoField']
    428428                    self._batched_insert(objs_without_pk, fields, batch_size)
    429429
    430430        return objs
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 7ca4954..58290ff 100644
    a b def construct_instance(form, instance, fields=None, exclude=None):  
    4545    cleaned_data = form.cleaned_data
    4646    file_field_list = []
    4747    for f in opts.fields:
    48         if not f.editable or isinstance(f, models.AutoField) \
     48        if not f.editable or f.get_internal_type() == 'AutoField' \
    4949                or f.name not in cleaned_data:
    5050            continue
    5151        if fields is not None and f.name not in fields:
    class BaseModelFormSet(BaseFormSet):  
    773773
    774774    def add_fields(self, form, index):
    775775        """Add a hidden field for the object's primary key."""
    776         from django.db.models import AutoField, OneToOneField, ForeignKey
     776        from django.db.models import OneToOneField, ForeignKey
    777777        self._pk_field = pk = self.model._meta.pk
    778778        # If a pk isn't editable, then it won't be on the form, so we need to
    779779        # add it here so we can tell which object is which when we get the
    class BaseModelFormSet(BaseFormSet):  
    782782        # True, so check for that as well.
    783783
    784784        def pk_is_not_editable(pk):
    785             return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField))
     785            return ((not pk.editable)
     786                or (pk.auto_created or pk.get_internal_type == 'AutoField')
    786787                or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))
    787788        if pk_is_not_editable(pk) or pk.name not in form.fields:
    788789            if form.is_bound:
  • tests/field_subclassing/fields.py

    diff --git a/tests/field_subclassing/fields.py b/tests/field_subclassing/fields.py
    index b94b237..a738433 100644
    a b from __future__ import unicode_literals  
    33import json
    44import warnings
    55
     6from django.core import exceptions
    67from django.db import models
    78from django.utils.encoding import force_text
    89from django.utils import six
    910from django.utils.deprecation import RemovedInDjango20Warning
    1011from django.utils.encoding import python_2_unicode_compatible
     12from django.utils.translation import ugettext_lazy as _
    1113
    1214
    1315# Catch warning about subfieldbase  -- remove in Django 2.0
    class JSONField(six.with_metaclass(models.SubfieldBase, models.TextField)):  
    9496class CustomTypedField(models.TextField):
    9597    def db_type(self, connection):
    9698        return 'custom_field'
     99
     100
     101class CustomAutoField(models.Field):
     102    description = _("Integer")
     103
     104    empty_strings_allowed = False
     105    default_error_messages = {
     106        'invalid': _("'%(value)s' value must be an integer."),
     107    }
     108
     109    def __init__(self, *args, **kwargs):
     110        kwargs['blank'] = True
     111        super(CustomAutoField, self).__init__(*args, **kwargs)
     112
     113    def get_internal_type(self):
     114        return "AutoField"
     115
     116    def to_python(self, value):
     117        if value is None:
     118            return value
     119        try:
     120            return int(value)
     121        except (TypeError, ValueError):
     122            raise exceptions.ValidationError(
     123                self.error_messages['invalid'],
     124                code='invalid',
     125                params={'value': value},
     126            )
     127
     128    def get_db_prep_value(self, value, connection, prepared=False):
     129        if not prepared:
     130            value = self.get_prep_value(value)
     131            value = connection.ops.validate_autopk_value(value)
     132        return value
     133
     134    def get_prep_value(self, value):
     135        value = super(CustomAutoField, self).get_prep_value(value)
     136        if value is None:
     137            return None
     138        return int(value)
     139
     140    def contribute_to_class(self, cls, name, **kwargs):
     141        assert not cls._meta.has_auto_field, \
     142            "A model can't have more than one AutoField."
     143        super(CustomAutoField, self).contribute_to_class(cls, name, **kwargs)
     144        cls._meta.has_auto_field = True
     145        cls._meta.auto_field = self
     146
     147    def formfield(self, **kwargs):
     148        return None
  • tests/field_subclassing/models.py

    diff --git a/tests/field_subclassing/models.py b/tests/field_subclassing/models.py
    index 66e765a..6107228 100644
    a b Tests for field subclassing.  
    44from django.db import models
    55from django.utils.encoding import force_text
    66
    7 from .fields import Small, SmallField, SmallerField, JSONField
     7from .fields import Small, SmallField, SmallerField, JSONField, CustomAutoField
    88from django.utils.encoding import python_2_unicode_compatible
    99
    1010
    class ChoicesModel(models.Model):  
    3333
    3434class DataModel(models.Model):
    3535    data = JSONField()
     36
     37
     38class CustomAutoFieldModel(models.Model):
     39    id = CustomAutoField(primary_key=True)
  • tests/field_subclassing/tests.py

    diff --git a/tests/field_subclassing/tests.py b/tests/field_subclassing/tests.py
    index 9e40d92..fac1997 100644
    a b from django.db import connection  
    77from django.test import TestCase
    88
    99from .fields import Small, CustomTypedField
    10 from .models import ChoicesModel, DataModel, MyModel, OtherModel
     10from .models import ChoicesModel, DataModel, MyModel, OtherModel, CustomAutoFieldModel
    1111
    1212
    1313class CustomField(TestCase):
    class CustomField(TestCase):  
    122122        with self.assertRaises(exceptions.ValidationError):
    123123            o.full_clean()
    124124
     125    def test_auto_field(self):
     126        o = CustomAutoFieldModel()
     127        self.assertEqual(o.pk, None)
     128        o.save()
     129        self.assertNotEqual(o.pk, None)
     130        self.assertTrue(isinstance(o.pk, int))
     131
    125132
    126133class TestDbType(TestCase):
    127134
Back to Top