Ticket #10785: custom_pk.2.diff

File custom_pk.2.diff, 5.3 KB (added by Alex, 6 years ago)
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 1d083cd..586d80c 100644
    a b class RelatedField(object): 
    132132                    v, field = getattr(v, v._meta.pk.name), v._meta.pk
    133133            except AttributeError:
    134134                pass
    135             if field:
    136                 if lookup_type in ('range', 'in'):
    137                     v = [v]
    138                 v = field.get_db_prep_lookup(lookup_type, v)
    139                 if isinstance(v, list):
    140                     v = v[0]
     135            if not field:
     136                field = self.rel.get_related_field()
     137            if lookup_type in ('range', 'in'):
     138                v = [v]
     139            v = field.get_db_prep_lookup(lookup_type, v)
     140            if isinstance(v, list):
     141                v = v[0]
    141142            return v
    142143
    143144        if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
    class ManyToManyField(RelatedField, Field): 
    955956        # A ManyToManyField is not represented by a single column,
    956957        # so return None.
    957958        return None
    958 
  • django/db/models/sql/where.py

    diff --git a/django/db/models/sql/where.py b/django/db/models/sql/where.py
    index ec0545c..0379aed 100644
    a b class Constraint(object): 
    278278            raise EmptyShortCircuit
    279279
    280280        return (self.alias, self.col, db_type), params
    281 
  • new file tests/modeltests/custom_pk/fields.py

    diff --git a/tests/modeltests/custom_pk/fields.py b/tests/modeltests/custom_pk/fields.py
    new file mode 100644
    index 0000000..319e42f
    - +  
     1import random
     2import string
     3
     4from django.db import models
     5
     6class MyWrapper(object):
     7    def __init__(self, value):
     8        self.value = value
     9
     10    def __repr__(self):
     11        return "<%s: %s>" % (self.__class__.__name__, self.value)
     12
     13    def __unicode__(self):
     14        return self.value
     15
     16    def __eq__(self, other):
     17        if isinstance(other, self.__class__):
     18            return self.value == other.value
     19        return self.value == other
     20
     21class MyAutoField(models.CharField):
     22    __metaclass__ = models.SubfieldBase
     23
     24    def __init__(self, *args, **kwargs):
     25        kwargs['max_length'] = 10
     26        super(MyAutoField, self).__init__(*args, **kwargs)
     27
     28    def pre_save(self, instance, add):
     29        value = getattr(instance, self.attname, None)
     30        if not value:
     31            value = MyWrapper(''.join(random.sample(string.lowercase, 10)))
     32            setattr(instance, self.attname, value)
     33        return value
     34
     35    def to_python(self, value):
     36        if not value:
     37            return
     38        if not isinstance(value, MyWrapper):
     39            value = MyWrapper(value)
     40        return value
     41
     42    def get_db_prep_save(self, value):
     43        if not value:
     44            return
     45        if isinstance(value, MyWrapper):
     46            return unicode(value)
     47        return value
     48
     49    def get_db_prep_value(self, value):
     50        if not value:
     51            return
     52        if isinstance(value, MyWrapper):
     53            return unicode(value)
     54        return value
  • tests/modeltests/custom_pk/models.py

    diff --git a/tests/modeltests/custom_pk/models.py b/tests/modeltests/custom_pk/models.py
    index 091f7f3..0323fec 100644
    a b this behavior by explicitly adding ``primary_key=True`` to a field. 
    99from django.conf import settings
    1010from django.db import models, transaction, IntegrityError
    1111
     12from fields import MyAutoField
     13
    1214class Employee(models.Model):
    1315    employee_code = models.IntegerField(primary_key=True, db_column = 'code')
    1416    first_name = models.CharField(max_length=20)
    class Business(models.Model): 
    2830    def __unicode__(self):
    2931        return self.name
    3032
     33class Bar(models.Model):
     34    id = MyAutoField(primary_key=True, db_index=True)
     35
     36    def __unicode__(self):
     37        return repr(self.pk)
     38
     39
     40class Foo(models.Model):
     41    bar = models.ForeignKey(Bar)
     42
    3143__test__ = {'API_TESTS':"""
    3244>>> dan = Employee(employee_code=123, first_name='Dan', last_name='Jones')
    3345>>> dan.save()
    DoesNotExist: Employee matching query does not exist. 
    121133...        print "Fail with %s" % type(e)
    122134Pass
    123135
     136>>> new_bar = Bar.objects.create()
     137>>> new_foo = Foo.objects.create(bar=new_bar)
     138>>> f = Foo.objects.get(bar=new_bar.pk)
     139>>> f == new_foo
     140True
     141>>> f.bar == new_bar
     142True
    124143"""}
    125144
    126145# SQLite lets objects be saved with an empty primary key, even though an
  • tests/modeltests/model_forms/models.py

    diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py
    index 992bb90..295c557 100644
    a b class ExplicitPK(models.Model): 
    189189    def __unicode__(self):
    190190        return self.key
    191191
     192
     193
    192194__test__ = {'API_TESTS': """
    193195>>> from django import forms
    194196>>> from django.forms.models import ModelForm, model_to_dict
    ValidationError: [u'Select a valid choice. z is not one of the available choices 
    14721474<tr><th><label for="id_description">Description:</label></th><td><input type="text" name="description" id="id_description" /></td></tr>
    14731475<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
    14741476
     1477
    14751478# Clean up
    14761479>>> import shutil
    14771480>>> shutil.rmtree(temp_storage_dir)
Back to Top