From 5a52d932ef4da8228d82673314341c2c86602248 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Mon, 5 Jun 2017 15:20:34 -0400 Subject: [PATCH] Replaced Model._get_pk_val() with pk property. Model.pk was added after _get_pk_val() and many places weren't simplified. --- django/contrib/admin/options.py | 6 ++---- django/contrib/admin/utils.py | 2 +- django/contrib/contenttypes/fields.py | 14 +++++++------- django/core/serializers/xml_serializer.py | 6 +++--- django/db/models/base.py | 10 +++++----- django/db/models/fields/__init__.py | 2 +- django/db/models/fields/related.py | 2 +- django/db/models/fields/related_descriptors.py | 4 ++-- django/db/models/fields/reverse_related.py | 2 +- django/db/models/query.py | 2 +- 10 files changed, 24 insertions(+), 26 deletions(-) diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index 2a447b7cff1..d0941a44a4e 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -1044,11 +1044,10 @@ class ModelAdmin(BaseModelAdmin): Determine the HttpResponse for the add_view stage. """ opts = obj._meta - pk_value = obj._get_pk_val() preserved_filters = self.get_preserved_filters(request) obj_url = reverse( 'admin:%s_%s_change' % (opts.app_label, opts.model_name), - args=(quote(pk_value),), + args=(quote(obj.pk),), current_app=self.admin_site.name, ) # Add a link to the object's change form if the user can edit the obj. @@ -1145,7 +1144,6 @@ class ModelAdmin(BaseModelAdmin): }) opts = self.model._meta - pk_value = obj._get_pk_val() preserved_filters = self.get_preserved_filters(request) msg_dict = { @@ -1170,7 +1168,7 @@ class ModelAdmin(BaseModelAdmin): self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), - args=(pk_value,), + args=(obj.pk,), current_app=self.admin_site.name) redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url) return HttpResponseRedirect(redirect_url) diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py index 05fbcebcb9b..5f3a83267dc 100644 --- a/django/contrib/admin/utils.py +++ b/django/contrib/admin/utils.py @@ -145,7 +145,7 @@ def get_deleted_objects(objs, opts, user, admin_site, using): % (admin_site.name, opts.app_label, opts.model_name), - None, (quote(obj._get_pk_val()),)) + None, (quote(obj.pk),)) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py index e4e759502c2..9394182aeee 100644 --- a/django/contrib/contenttypes/fields.py +++ b/django/contrib/contenttypes/fields.py @@ -203,7 +203,7 @@ class GenericForeignKey: model) return (ret_val, - lambda obj: (obj._get_pk_val(), obj.__class__), + lambda obj: (obj.pk, obj.__class__), gfk_key, True, self.name) @@ -229,7 +229,7 @@ class GenericForeignKey: rel_obj = None else: if rel_obj and (ct_id != self.get_content_type(obj=rel_obj, using=instance._state.db).id or - rel_obj._meta.pk.to_python(pk_val) != rel_obj._get_pk_val()): + rel_obj._meta.pk.to_python(pk_val) != rel_obj.pk): rel_obj = None if rel_obj is not None: @@ -249,7 +249,7 @@ class GenericForeignKey: fk = None if value is not None: ct = self.get_content_type(obj=value) - fk = value._get_pk_val() + fk = value.pk setattr(instance, self.ct_field, ct) setattr(instance, self.fk_field, fk) @@ -397,7 +397,7 @@ class GenericRelation(ForeignObject): def value_to_string(self, obj): qs = getattr(obj, self.name).all() - return str([instance._get_pk_val() for instance in qs]) + return str([instance.pk for instance in qs]) def contribute_to_class(self, cls, name, **kwargs): kwargs['private_only'] = True @@ -490,7 +490,7 @@ def create_generic_related_manager(superclass, rel): self.content_type_field_name = rel.field.content_type_field_name self.object_id_field_name = rel.field.object_id_field_name self.prefetch_cache_name = rel.field.attname - self.pk_val = instance._get_pk_val() + self.pk_val = instance.pk self.core_filters = { '%s__pk' % self.content_type_field_name: content_type.id, @@ -529,7 +529,7 @@ def create_generic_related_manager(superclass, rel): query = { '%s__pk' % self.content_type_field_name: self.content_type.id, - '%s__in' % self.object_id_field_name: {obj._get_pk_val() for obj in instances} + '%s__in' % self.object_id_field_name: {obj.pk for obj in instances} } # We (possibly) need to convert object IDs to the type of the @@ -537,7 +537,7 @@ def create_generic_related_manager(superclass, rel): object_id_converter = instances[0]._meta.pk.to_python return (queryset.filter(**query), lambda relobj: object_id_converter(getattr(relobj, self.object_id_field_name)), - lambda obj: obj._get_pk_val(), + lambda obj: obj.pk, False, self.prefetch_cache_name) diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py index 23a07ef43a1..1fb00938508 100644 --- a/django/core/serializers/xml_serializer.py +++ b/django/core/serializers/xml_serializer.py @@ -49,7 +49,7 @@ class Serializer(base.Serializer): self.indent(1) attrs = OrderedDict([("model", str(obj._meta))]) if not self.use_natural_primary_keys or not hasattr(obj, 'natural_key'): - obj_pk = obj._get_pk_val() + obj_pk = obj.pk if obj_pk is not None: attrs['pk'] = str(obj_pk) @@ -79,7 +79,7 @@ class Serializer(base.Serializer): self.xml.characters(field.value_to_string(obj)) except UnserializableContentError: raise ValueError("%s.%s (pk:%s) contains unserializable characters" % ( - obj.__class__.__name__, field.name, obj._get_pk_val())) + obj.__class__.__name__, field.name, obj.pk)) else: self.xml.addQuickElement("None") @@ -130,7 +130,7 @@ class Serializer(base.Serializer): else: def handle_m2m(value): self.xml.addQuickElement("object", attrs={ - 'pk': str(value._get_pk_val()) + 'pk': str(value.pk) }) for relobj in getattr(obj, field.name).iterator(): handle_m2m(relobj) diff --git a/django/db/models/base.py b/django/db/models/base.py index 16c7d3636f4..4673920ade3 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -511,15 +511,15 @@ class Model(metaclass=ModelBase): return False if self._meta.concrete_model != other._meta.concrete_model: return False - my_pk = self._get_pk_val() + my_pk = self.pk if my_pk is None: return self is other - return my_pk == other._get_pk_val() + return my_pk == other.pk def __hash__(self): - if self._get_pk_val() is None: + if self.pk is None: raise TypeError("Model instances without primary key value are unhashable") - return hash(self._get_pk_val()) + return hash(self.pk) def __reduce__(self): data = self.__dict__ @@ -867,7 +867,7 @@ class Model(metaclass=ModelBase): def delete(self, using=None, keep_parents=False): using = using or router.db_for_write(self.__class__, instance=self) - assert self._get_pk_val() is not None, ( + assert self.pk is not None, ( "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) ) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 09f9940b6b5..ac8eb778fa8 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -799,7 +799,7 @@ class Field(RegisterLookupMixin): for x in rel_model._default_manager.complex_filter( limit_choices_to)] else: - lst = [(x._get_pk_val(), smart_text(x)) + lst = [(x.pk, smart_text(x)) for x in rel_model._default_manager.complex_filter( limit_choices_to)] return first_choice + lst diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 684f88e8b6a..f7553550795 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -1604,7 +1604,7 @@ class ManyToManyField(RelatedField): initial = defaults['initial'] if callable(initial): initial = initial() - defaults['initial'] = [i._get_pk_val() for i in initial] + defaults['initial'] = [i.pk for i in initial] return super().formfield(**defaults) def db_check(self, connection): diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py index 86da637f26f..0d7507f33f7 100644 --- a/django/db/models/fields/related_descriptors.py +++ b/django/db/models/fields/related_descriptors.py @@ -319,7 +319,7 @@ class ReverseOneToOneDescriptor: rel_obj_attr = attrgetter(self.related.field.attname) def instance_attr(obj): - return obj._get_pk_val() + return obj.pk instances_dict = {instance_attr(inst): inst for inst in instances} query = {'%s__in' % self.related.field.name: instances} @@ -354,7 +354,7 @@ class ReverseOneToOneDescriptor: try: rel_obj = getattr(instance, self.cache_name) except AttributeError: - related_pk = instance._get_pk_val() + related_pk = instance.pk if related_pk is None: rel_obj = None else: diff --git a/django/db/models/fields/reverse_related.py b/django/db/models/fields/reverse_related.py index 36396ac2822..ab8b3ffe588 100644 --- a/django/db/models/fields/reverse_related.py +++ b/django/db/models/fields/reverse_related.py @@ -122,7 +122,7 @@ class ForeignObjectRel: initially for utilization by RelatedFieldListFilter. """ return (blank_choice if include_blank else []) + [ - (x._get_pk_val(), str(x)) for x in self.related_model._default_manager.all() + (x.pk, str(x)) for x in self.related_model._default_manager.all() ] def is_hidden(self): diff --git a/django/db/models/query.py b/django/db/models/query.py index bc9ee1c5f8d..8e2aa0a1414 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -583,7 +583,7 @@ class QuerySet: qs = self.filter(pk__in=id_list).order_by() else: qs = self._clone() - return {obj._get_pk_val(): obj for obj in qs} + return {obj.pk: obj for obj in qs} def delete(self): """Delete the records in the current QuerySet."""