Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #683 -- Lightly refactored meta.fields.Field to add an attname …

…attribute.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@1150 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 2ef937d0fdd607900f67ecc932309d87167ba89a 1 parent aae50fc
Adrian Holovaty authored November 09, 2005
20  django/contrib/admin/views/main.py
@@ -214,7 +214,7 @@ def change_list(request, app_label, module_name):
214 214
                         ((lookup_val is None and ' class="selected"' or ''),
215 215
                         get_query_string(params, {}, [lookup_kwarg])))
216 216
                     for val in lookup_choices:
217  
-                        pk_val = getattr(val, f.rel.to.pk.column)
  217
+                        pk_val = getattr(val, f.rel.to.pk.attname)
218 218
                         filter_template.append('<li%s><a href="%s">%r</a></li>\n' % \
219 219
                             ((lookup_val == str(pk_val) and ' class="selected"' or ''),
220 220
                             get_query_string(params, {lookup_kwarg: pk_val}), val))
@@ -378,7 +378,7 @@ def change_list(request, app_label, module_name):
378 378
                         capfirst(f.verbose_name)))
379 379
         raw_template.append('</tr>\n</thead>\n')
380 380
         # Result rows.
381  
-        pk = lookup_opts.pk.name
  381
+        pk = lookup_opts.pk.attname
382 382
         for i, result in enumerate(result_list):
383 383
             raw_template.append('<tr class="row%s">\n' % (i % 2 + 1))
384 384
             for j, field_name in enumerate(lookup_opts.admin.list_display):
@@ -393,7 +393,7 @@ def change_list(request, app_label, module_name):
393 393
                     except ObjectDoesNotExist:
394 394
                         result_repr = EMPTY_CHANGELIST_VALUE
395 395
                 else:
396  
-                    field_val = getattr(result, f.column)
  396
+                    field_val = getattr(result, f.attname)
397 397
                     # Foreign-key fields are special: Use the repr of the
398 398
                     # related object.
399 399
                     if isinstance(f.rel, meta.ManyToOne):
@@ -785,7 +785,7 @@ def add_stage(request, app_label, module_name, show_delete=False, form_url='', p
785 785
                     new_data.setlist(f.name, new_data[f.name].split(","))
786 786
             manipulator.do_html2python(new_data)
787 787
             new_object = manipulator.save(new_data)
788  
-            pk_value = getattr(new_object, opts.pk.column)
  788
+            pk_value = getattr(new_object, opts.pk.attname)
789 789
             log.log_action(request.user.id, opts.get_content_type_id(), pk_value, repr(new_object), log.ADDITION)
790 790
             msg = 'The %s "%s" was added successfully.' % (opts.verbose_name, new_object)
791 791
             # Here, we distinguish between different save types by checking for
@@ -887,7 +887,7 @@ def change_stage(request, app_label, module_name, object_id):
887 887
                     new_data.setlist(f.name, new_data[f.name].split(","))
888 888
             manipulator.do_html2python(new_data)
889 889
             new_object = manipulator.save(new_data)
890  
-            pk_value = getattr(new_object, opts.pk.column)
  890
+            pk_value = getattr(new_object, opts.pk.attname)
891 891
 
892 892
             # Construct the change message.
893 893
             change_message = []
@@ -925,19 +925,19 @@ def change_stage(request, app_label, module_name, object_id):
925 925
         new_data = {}
926 926
         obj = manipulator.original_object
927 927
         for f in opts.fields:
928  
-            new_data.update(_get_flattened_data(f, getattr(obj, f.column)))
  928
+            new_data.update(_get_flattened_data(f, getattr(obj, f.attname)))
929 929
         for f in opts.many_to_many:
930 930
             get_list_func = getattr(obj, 'get_%s_list' % f.rel.singular)
931 931
             if f.rel.raw_id_admin:
932  
-                new_data[f.name] = ",".join([str(getattr(i, f.rel.to.pk.column)) for i in get_list_func()])
  932
+                new_data[f.name] = ",".join([str(getattr(i, f.rel.to.pk.attname)) for i in get_list_func()])
933 933
             elif not f.rel.edit_inline:
934  
-                new_data[f.name] = [getattr(i, f.rel.to.pk.column) for i in get_list_func()]
  934
+                new_data[f.name] = [getattr(i, f.rel.to.pk.attname) for i in get_list_func()]
935 935
         for rel_obj, rel_field in inline_related_objects:
936 936
             var_name = rel_obj.object_name.lower()
937 937
             for i, rel_instance in enumerate(getattr(obj, 'get_%s_list' % opts.get_rel_object_method_name(rel_obj, rel_field))()):
938 938
                 for f in rel_obj.fields:
939 939
                     if f.editable and f != rel_field:
940  
-                        for k, v in _get_flattened_data(f, getattr(rel_instance, f.column)).items():
  940
+                        for k, v in _get_flattened_data(f, getattr(rel_instance, f.attname)).items():
941 941
                             new_data['%s.%d.%s' % (var_name, i, k)] = v
942 942
                 for f in rel_obj.many_to_many:
943 943
                     new_data['%s.%d.%s' % (var_name, i, f.column)] = [j.id for j in getattr(rel_instance, 'get_%s_list' % f.rel.singular)()]
@@ -1026,7 +1026,7 @@ def _get_deleted_objects(deleted_objects, perms_needed, user, obj, opts, current
1026 1026
                     # Display a link to the admin page.
1027 1027
                     nh(deleted_objects, current_depth, ['%s: <a href="../../../../%s/%s/%s/">%r</a>' % \
1028 1028
                         (capfirst(rel_opts.verbose_name), rel_opts.app_label, rel_opts.module_name,
1029  
-                        getattr(sub_obj, rel_opts.pk.column), sub_obj), []])
  1029
+                        getattr(sub_obj, rel_opts.pk.attname), sub_obj), []])
1030 1030
                 _get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, rel_opts, current_depth+2)
1031 1031
         else:
1032 1032
             has_related_objs = False
108  django/core/meta/__init__.py
@@ -748,7 +748,7 @@ def method_init(opts, self, *args, **kwargs):
748 748
                 except KeyError:
749 749
                     try:
750 750
                         # Object instance wasn't passed in -- must be an ID.
751  
-                        val = kwargs.pop(f.column)
  751
+                        val = kwargs.pop(f.attname)
752 752
                     except KeyError:
753 753
                         val = f.get_default()
754 754
                 else:
@@ -760,17 +760,17 @@ def method_init(opts, self, *args, **kwargs):
760 760
                             val = getattr(rel_obj, f.rel.field_name)
761 761
                         except AttributeError:
762 762
                             raise TypeError, "Invalid value: %r should be a %s instance, not a %s" % (f.name, f.rel.to, type(rel_obj))
763  
-                setattr(self, f.column, val)
  763
+                setattr(self, f.attname, val)
764 764
             else:
765  
-                val = kwargs.pop(f.name, f.get_default())
766  
-                setattr(self, f.name, val)
  765
+                val = kwargs.pop(f.attname, f.get_default())
  766
+                setattr(self, f.attname, val)
767 767
         if kwargs:
768 768
             raise TypeError, "'%s' is an invalid keyword argument for this function" % kwargs.keys()[0]
769 769
     for i, arg in enumerate(args):
770  
-        setattr(self, opts.fields[i].column, arg)
  770
+        setattr(self, opts.fields[i].attname, arg)
771 771
 
772 772
 def method_eq(opts, self, other):
773  
-    return isinstance(other, self.__class__) and getattr(self, opts.pk.column) == getattr(other, opts.pk.column)
  773
+    return isinstance(other, self.__class__) and getattr(self, opts.pk.attname) == getattr(other, opts.pk.attname)
774 774
 
775 775
 def method_save(opts, self):
776 776
     # Run any pre-save hooks.
@@ -780,7 +780,7 @@ def method_save(opts, self):
780 780
     cursor = db.db.cursor()
781 781
 
782 782
     # First, try an UPDATE. If that doesn't update anything, do an INSERT.
783  
-    pk_val = getattr(self, opts.pk.column)
  783
+    pk_val = getattr(self, opts.pk.attname)
784 784
     pk_set = bool(pk_val)
785 785
     record_exists = True
786 786
     if pk_set:
@@ -788,33 +788,33 @@ def method_save(opts, self):
788 788
         cursor.execute("SELECT 1 FROM %s WHERE %s=%%s LIMIT 1" % (opts.db_table, opts.pk.column), [pk_val])
789 789
         # If it does already exist, do an UPDATE.
790 790
         if cursor.fetchone():
791  
-            db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.column), False)) for f in non_pks]
  791
+            db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.attname), False)) for f in non_pks]
792 792
             cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % (opts.db_table,
793  
-                ','.join(['%s=%%s' % f.column for f in non_pks]), opts.pk.column),
  793
+                ','.join(['%s=%%s' % f.column for f in non_pks]), opts.pk.attname),
794 794
                 db_values + [pk_val])
795 795
         else:
796 796
             record_exists = False
797 797
     if not pk_set or not record_exists:
798 798
         field_names = [f.column for f in opts.fields if not isinstance(f, AutoField)]
799 799
         placeholders = ['%s'] * len(field_names)
800  
-        db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.column), True)) for f in opts.fields if not isinstance(f, AutoField)]
  800
+        db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.attname), True)) for f in opts.fields if not isinstance(f, AutoField)]
801 801
         if opts.order_with_respect_to:
802 802
             field_names.append('_order')
803 803
             # TODO: This assumes the database supports subqueries.
804 804
             placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \
805 805
                 (opts.db_table, opts.order_with_respect_to.column))
806  
-            db_values.append(getattr(self, opts.order_with_respect_to.column))
  806
+            db_values.append(getattr(self, opts.order_with_respect_to.attname))
807 807
         cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % (opts.db_table,
808 808
             ','.join(field_names), ','.join(placeholders)), db_values)
809 809
         if opts.has_auto_field:
810  
-            setattr(self, opts.pk.column, db.get_last_insert_id(cursor, opts.db_table, opts.pk.column))
  810
+            setattr(self, opts.pk.attname, db.get_last_insert_id(cursor, opts.db_table, opts.pk.column))
811 811
     db.db.commit()
812 812
     # Run any post-save hooks.
813 813
     if hasattr(self, '_post_save'):
814 814
         self._post_save()
815 815
 
816 816
 def method_delete(opts, self):
817  
-    assert getattr(self, opts.pk.column) is not None, "%r can't be deleted because it doesn't have an ID."
  817
+    assert getattr(self, opts.pk.attname) is not None, "%r can't be deleted because it doesn't have an ID."
818 818
     # Run any pre-delete hooks.
819 819
     if hasattr(self, '_pre_delete'):
820 820
         self._pre_delete()
@@ -833,15 +833,15 @@ def method_delete(opts, self):
833 833
                 sub_obj.delete()
834 834
     for rel_opts, rel_field in opts.get_all_related_many_to_many_objects():
835 835
         cursor.execute("DELETE FROM %s WHERE %s_id=%%s" % (rel_field.get_m2m_db_table(rel_opts),
836  
-            self._meta.object_name.lower()), [getattr(self, opts.pk.column)])
  836
+            self._meta.object_name.lower()), [getattr(self, opts.pk.attname)])
837 837
     for f in opts.many_to_many:
838 838
         cursor.execute("DELETE FROM %s WHERE %s_id=%%s" % (f.get_m2m_db_table(opts), self._meta.object_name.lower()),
839  
-            [getattr(self, opts.pk.column)])
840  
-    cursor.execute("DELETE FROM %s WHERE %s=%%s" % (opts.db_table, opts.pk.column), [getattr(self, opts.pk.column)])
  839
+            [getattr(self, opts.pk.attname)])
  840
+    cursor.execute("DELETE FROM %s WHERE %s=%%s" % (opts.db_table, opts.pk.column), [getattr(self, opts.pk.attname)])
841 841
     db.db.commit()
842  
-    setattr(self, opts.pk.column, None)
  842
+    setattr(self, opts.pk.attname, None)
843 843
     for f in opts.fields:
844  
-        if isinstance(f, FileField) and getattr(self, f.column):
  844
+        if isinstance(f, FileField) and getattr(self, f.attname):
845 845
             file_name = getattr(self, 'get_%s_filename' % f.name)()
846 846
             # If the file exists and no other object of this type references it,
847 847
             # delete it from the filesystem.
@@ -856,7 +856,7 @@ def method_get_next_in_order(opts, order_field, self):
856 856
         self._next_in_order_cache = opts.get_model_module().get_object(order_by=('_order',),
857 857
             where=['_order > (SELECT _order FROM %s WHERE %s=%%s)' % (opts.db_table, opts.pk.column),
858 858
                 '%s=%%s' % order_field.column], limit=1,
859  
-            params=[getattr(self, opts.pk.column), getattr(self, order_field.column)])
  859
+            params=[getattr(self, opts.pk.attname), getattr(self, order_field.attname)])
860 860
     return self._next_in_order_cache
861 861
 
862 862
 def method_get_previous_in_order(opts, order_field, self):
@@ -864,7 +864,7 @@ def method_get_previous_in_order(opts, order_field, self):
864 864
         self._previous_in_order_cache = opts.get_model_module().get_object(order_by=('-_order',),
865 865
             where=['_order < (SELECT _order FROM %s WHERE %s=%%s)' % (opts.db_table, opts.pk.column),
866 866
                 '%s=%%s' % order_field.column], limit=1,
867  
-            params=[getattr(self, opts.pk.column), getattr(self, order_field.column)])
  867
+            params=[getattr(self, opts.pk.attname), getattr(self, order_field.attname)])
868 868
     return self._previous_in_order_cache
869 869
 
870 870
 # RELATIONSHIP METHODS #####################
@@ -873,7 +873,7 @@ def method_get_previous_in_order(opts, order_field, self):
873 873
 def method_get_many_to_one(field_with_rel, self):
874 874
     cache_var = field_with_rel.get_cache_name()
875 875
     if not hasattr(self, cache_var):
876  
-        val = getattr(self, field_with_rel.column)
  876
+        val = getattr(self, field_with_rel.attname)
877 877
         mod = field_with_rel.rel.to.get_model_module()
878 878
         if val is None:
879 879
             raise getattr(mod, '%sDoesNotExist' % field_with_rel.rel.to.object_name)
@@ -893,7 +893,7 @@ def method_get_many_to_many(field_with_rel, self):
893 893
             field_with_rel.get_m2m_db_table(self._meta), rel.pk.column,
894 894
             rel.object_name.lower(), self._meta.object_name.lower(), rel.get_order_sql('a'))
895 895
         cursor = db.db.cursor()
896  
-        cursor.execute(sql, [getattr(self, self._meta.pk.column)])
  896
+        cursor.execute(sql, [getattr(self, self._meta.pk.attname)])
897 897
         setattr(self, cache_var, [getattr(mod, rel.object_name)(*row) for row in cursor.fetchall()])
898 898
     return getattr(self, cache_var)
899 899
 
@@ -914,7 +914,7 @@ def method_set_many_to_many(rel_field, self, id_list):
914 914
     rel = rel_field.rel.to
915 915
     m2m_table = rel_field.get_m2m_db_table(self._meta)
916 916
     cursor = db.db.cursor()
917  
-    this_id = getattr(self, self._meta.pk.column)
  917
+    this_id = getattr(self, self._meta.pk.attname)
918 918
     if ids_to_delete:
919 919
         sql = "DELETE FROM %s WHERE %s_id = %%s AND %s_id IN (%s)" % (m2m_table, self._meta.object_name.lower(), rel.object_name.lower(), ','.join(map(str, ids_to_delete)))
920 920
         cursor.execute(sql, [this_id])
@@ -941,11 +941,11 @@ def method_get_related(method_name, rel_mod, rel_field, self, **kwargs):
941 941
 # Handles adding related objects.
942 942
 # Example: Poll.add_choice()
943 943
 def method_add_related(rel_obj, rel_mod, rel_field, self, *args, **kwargs):
944  
-    init_kwargs = dict(zip([f.name for f in rel_obj.fields if f != rel_field and not isinstance(f, AutoField)], args))
  944
+    init_kwargs = dict(zip([f.attname for f in rel_obj.fields if f != rel_field and not isinstance(f, AutoField)], args))
945 945
     init_kwargs.update(kwargs)
946 946
     for f in rel_obj.fields:
947 947
         if isinstance(f, AutoField):
948  
-            init_kwargs[f.name] = None
  948
+            init_kwargs[f.attname] = None
949 949
     init_kwargs[rel_field.name] = self
950 950
     obj = rel_mod.Klass(**init_kwargs)
951 951
     obj.save()
@@ -954,7 +954,7 @@ def method_add_related(rel_obj, rel_mod, rel_field, self, *args, **kwargs):
954 954
 # Handles related many-to-many object retrieval.
955 955
 # Examples: Album.get_song(), Album.get_song_list(), Album.get_song_count()
956 956
 def method_get_related_many_to_many(method_name, opts, rel_mod, rel_field, self, **kwargs):
957  
-    kwargs['%s__%s__exact' % (rel_field.name, opts.pk.name)] = getattr(self, opts.pk.column)
  957
+    kwargs['%s__%s__exact' % (rel_field.name, opts.pk.name)] = getattr(self, opts.pk.attname)
958 958
     return getattr(rel_mod, method_name)(**kwargs)
959 959
 
960 960
 # Handles setting many-to-many related objects.
@@ -963,7 +963,7 @@ def method_set_related_many_to_many(rel_opts, rel_field, self, id_list):
963 963
     id_list = map(int, id_list) # normalize to integers
964 964
     rel = rel_field.rel.to
965 965
     m2m_table = rel_field.get_m2m_db_table(rel_opts)
966  
-    this_id = getattr(self, self._meta.pk.column)
  966
+    this_id = getattr(self, self._meta.pk.attname)
967 967
     cursor = db.db.cursor()
968 968
     cursor.execute("DELETE FROM %s WHERE %s_id = %%s" % (m2m_table, rel.object_name.lower()), [this_id])
969 969
     sql = "INSERT INTO %s (%s_id, %s_id) VALUES (%%s, %%s)" % (m2m_table, rel.object_name.lower(), rel_opts.object_name.lower())
@@ -992,7 +992,7 @@ def method_get_order(ordered_obj, self):
992 992
 
993 993
 def method_get_next_or_previous(get_object_func, field, is_next, self, **kwargs):
994 994
     kwargs.setdefault('where', []).append('%s %s %%s' % (field.column, (is_next and '>' or '<')))
995  
-    kwargs.setdefault('params', []).append(str(getattr(self, field.name)))
  995
+    kwargs.setdefault('params', []).append(str(getattr(self, field.attname)))
996 996
     kwargs['order_by'] = [(not is_next and '-' or '') + field.name]
997 997
     kwargs['limit'] = 1
998 998
     return get_object_func(**kwargs)
@@ -1000,18 +1000,18 @@ def method_get_next_or_previous(get_object_func, field, is_next, self, **kwargs)
1000 1000
 # CHOICE-RELATED METHODS ###################
1001 1001
 
1002 1002
 def method_get_display_value(field, self):
1003  
-    value = getattr(self, field.column)
  1003
+    value = getattr(self, field.attname)
1004 1004
     return dict(field.choices).get(value, value)
1005 1005
 
1006 1006
 # FILE-RELATED METHODS #####################
1007 1007
 
1008 1008
 def method_get_file_filename(field, self):
1009  
-    return os.path.join(settings.MEDIA_ROOT, getattr(self, field.name))
  1009
+    return os.path.join(settings.MEDIA_ROOT, getattr(self, field.attname))
1010 1010
 
1011 1011
 def method_get_file_url(field, self):
1012  
-    if getattr(self, field.name): # value is not blank
  1012
+    if getattr(self, field.attname): # value is not blank
1013 1013
         import urlparse
1014  
-        return urlparse.urljoin(settings.MEDIA_URL, getattr(self, field.name)).replace('\\', '/')
  1014
+        return urlparse.urljoin(settings.MEDIA_URL, getattr(self, field.attname)).replace('\\', '/')
1015 1015
     return ''
1016 1016
 
1017 1017
 def method_get_file_size(field, self):
@@ -1036,7 +1036,7 @@ def method_save_file(field, self, filename, raw_contents):
1036 1036
             filename = filename[:dot_index] + '_' + filename[dot_index:]
1037 1037
 
1038 1038
     # Write the file to disk.
1039  
-    setattr(self, field.name, filename)
  1039
+    setattr(self, field.attname, filename)
1040 1040
     fp = open(getattr(self, 'get_%s_filename' % field.name)(), 'wb')
1041 1041
     fp.write(raw_contents)
1042 1042
     fp.close()
@@ -1363,7 +1363,7 @@ def function_get_in_bulk(opts, klass, *args, **kwargs):
1363 1363
     kwargs['where'] = ["%s.%s IN (%s)" % (opts.db_table, opts.pk.column, ",".join(['%s'] * len(id_list)))]
1364 1364
     kwargs['params'] = id_list
1365 1365
     obj_list = function_get_list(opts, klass, **kwargs)
1366  
-    return dict([(getattr(o, opts.pk.column), o) for o in obj_list])
  1366
+    return dict([(getattr(o, opts.pk.attname), o) for o in obj_list])
1367 1367
 
1368 1368
 def function_get_latest(opts, klass, does_not_exist_exception, **kwargs):
1369 1369
     kwargs['order_by'] = ('-' + opts.get_latest_by,)
@@ -1433,8 +1433,8 @@ def manipulator_init(opts, add, change, self, obj_key=None):
1433 1433
                 lookup_kwargs = opts.one_to_one_field.rel.limit_choices_to
1434 1434
                 lookup_kwargs['%s__exact' % opts.one_to_one_field.rel.field_name] = obj_key
1435 1435
                 _ = opts.one_to_one_field.rel.to.get_model_module().get_object(**lookup_kwargs)
1436  
-                params = dict([(f.column, f.get_default()) for f in opts.fields])
1437  
-                params[opts.pk.column] = obj_key
  1436
+                params = dict([(f.attname, f.get_default()) for f in opts.fields])
  1437
+                params[opts.pk.attname] = obj_key
1438 1438
                 self.original_object = opts.get_model_module().Klass(**params)
1439 1439
             else:
1440 1440
                 raise
@@ -1470,12 +1470,12 @@ def manipulator_save(opts, klass, add, change, self, new_data):
1470 1470
         # Fields with auto_now_add are another special case; they should keep
1471 1471
         # their original value in the change stage.
1472 1472
         if change and getattr(f, 'auto_now_add', False):
1473  
-            params[f.column] = getattr(self.original_object, f.name)
  1473
+            params[f.attname] = getattr(self.original_object, f.attname)
1474 1474
         else:
1475  
-            params[f.column] = f.get_manipulator_new_data(new_data)
  1475
+            params[f.attname] = f.get_manipulator_new_data(new_data)
1476 1476
 
1477 1477
     if change:
1478  
-        params[opts.pk.column] = self.obj_key
  1478
+        params[opts.pk.attname] = self.obj_key
1479 1479
 
1480 1480
     # First, save the basic object itself.
1481 1481
     new_object = klass(**params)
@@ -1490,7 +1490,7 @@ def manipulator_save(opts, klass, add, change, self, new_data):
1490 1490
     if change:
1491 1491
         self.fields_added, self.fields_changed, self.fields_deleted = [], [], []
1492 1492
         for f in opts.fields:
1493  
-            if not f.primary_key and str(getattr(self.original_object, f.column)) != str(getattr(new_object, f.column)):
  1493
+            if not f.primary_key and str(getattr(self.original_object, f.attname)) != str(getattr(new_object, f.attname)):
1494 1494
                 self.fields_changed.append(f.verbose_name)
1495 1495
 
1496 1496
     # Save many-to-many objects. Example: Poll.set_sites()
@@ -1526,7 +1526,7 @@ def manipulator_save(opts, klass, add, change, self, new_data):
1526 1526
                 old_rel_obj = None
1527 1527
                 if rel_new_data[rel_opts.pk.name][0]:
1528 1528
                     try:
1529  
-                        old_rel_obj = getattr(self.original_object, 'get_%s' % opts.get_rel_object_method_name(rel_opts, rel_field))(**{'%s__exact' % rel_opts.pk.name: rel_new_data[rel_opts.pk.name][0]})
  1529
+                        old_rel_obj = getattr(self.original_object, 'get_%s' % opts.get_rel_object_method_name(rel_opts, rel_field))(**{'%s__exact' % rel_opts.pk.name: rel_new_data[rel_opts.pk.attname][0]})
1530 1530
                     except ObjectDoesNotExist:
1531 1531
                         pass
1532 1532
 
@@ -1540,16 +1540,16 @@ def manipulator_save(opts, klass, add, change, self, new_data):
1540 1540
                 # given, use a default value. FileFields are also a special
1541 1541
                 # case, because they'll be dealt with later.
1542 1542
                 if change and (isinstance(f, FileField) or not f.editable):
1543  
-                    if rel_new_data.get(rel_opts.pk.name, False) and rel_new_data[rel_opts.pk.name][0]:
1544  
-                        params[f.column] = getattr(old_rel_obj, f.column)
  1543
+                    if rel_new_data.get(rel_opts.pk.attname, False) and rel_new_data[rel_opts.pk.attname][0]:
  1544
+                        params[f.attname] = getattr(old_rel_obj, f.attname)
1545 1545
                     else:
1546  
-                        params[f.column] = f.get_default()
  1546
+                        params[f.attname] = f.get_default()
1547 1547
                 elif f == rel_field:
1548  
-                    params[f.column] = getattr(new_object, rel_field.rel.field_name)
  1548
+                    params[f.attname] = getattr(new_object, rel_field.rel.field_name)
1549 1549
                 elif add and isinstance(f, AutoField):
1550  
-                    params[f.column] = None
  1550
+                    params[f.attname] = None
1551 1551
                 else:
1552  
-                    params[f.column] = f.get_manipulator_new_data(rel_new_data, rel=True)
  1552
+                    params[f.attname] = f.get_manipulator_new_data(rel_new_data, rel=True)
1553 1553
                 # Related links are a special case, because we have to
1554 1554
                 # manually set the "content_type_id" and "object_id" fields.
1555 1555
                 if opts.has_related_links and rel_opts.module_name == 'relatedlinks':
@@ -1566,7 +1566,7 @@ def manipulator_save(opts, klass, add, change, self, new_data):
1566 1566
 
1567 1567
                 # Save any uploaded files.
1568 1568
                 for f in rel_opts.fields:
1569  
-                    if isinstance(f, FileField) and rel_new_data.get(f.name, False):
  1569
+                    if isinstance(f, FileField) and rel_new_data.get(f.attname, False):
1570 1570
                         f.save_file(rel_new_data, new_rel_obj, change and old_rel_obj or None, old_rel_obj is not None, rel=True)
1571 1571
 
1572 1572
                 # Calculate whether any fields have changed.
@@ -1575,19 +1575,19 @@ def manipulator_save(opts, klass, add, change, self, new_data):
1575 1575
                         self.fields_added.append('%s "%r"' % (rel_opts.verbose_name, new_rel_obj))
1576 1576
                     else:
1577 1577
                         for f in rel_opts.fields:
1578  
-                            if not f.primary_key and f != rel_field and str(getattr(old_rel_obj, f.column)) != str(getattr(new_rel_obj, f.column)):
  1578
+                            if not f.primary_key and f != rel_field and str(getattr(old_rel_obj, f.attname)) != str(getattr(new_rel_obj, f.attname)):
1579 1579
                                 self.fields_changed.append('%s for %s "%r"' % (f.verbose_name, rel_opts.verbose_name, new_rel_obj))
1580 1580
 
1581 1581
                 # Save many-to-many objects.
1582 1582
                 for f in rel_opts.many_to_many:
1583 1583
                     if not f.rel.edit_inline:
1584  
-                        was_changed = getattr(new_rel_obj, 'set_%s' % f.name)(rel_new_data[f.name])
  1584
+                        was_changed = getattr(new_rel_obj, 'set_%s' % f.name)(rel_new_data[f.attname])
1585 1585
                         if change and was_changed:
1586 1586
                             self.fields_changed.append('%s for %s "%s"' % (f.verbose_name, rel_opts.verbose_name, new_rel_obj))
1587 1587
 
1588 1588
             # If, in the change stage, all of the core fields were blank and
1589 1589
             # the primary key (ID) was provided, delete the item.
1590  
-            if change and all_cores_blank and rel_new_data.has_key(rel_opts.pk.name) and rel_new_data[rel_opts.pk.name][0]:
  1590
+            if change and all_cores_blank and rel_new_data.has_key(rel_opts.pk.attname) and rel_new_data[rel_opts.pk.attname][0]:
1591 1591
                 new_rel_obj.delete()
1592 1592
                 self.fields_deleted.append('%s "%r"' % (rel_opts.verbose_name, old_rel_obj))
1593 1593
 
@@ -1606,7 +1606,7 @@ def manipulator_validator_unique_together(field_name_list, opts, self, field_dat
1606 1606
     else:
1607 1607
         kwargs = {'%s__iexact' % field_name_list[0]: field_data}
1608 1608
     for f in field_list[1:]:
1609  
-        field_val = all_data.get(f.column, None)
  1609
+        field_val = all_data.get(f.attname, None)
1610 1610
         if field_val is None:
1611 1611
             # This will be caught by another validator, assuming the field
1612 1612
             # doesn't have blank=True.
@@ -1620,7 +1620,7 @@ def manipulator_validator_unique_together(field_name_list, opts, self, field_dat
1620 1620
         old_obj = mod.get_object(**kwargs)
1621 1621
     except ObjectDoesNotExist:
1622 1622
         return
1623  
-    if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.column) == getattr(old_obj, opts.pk.column):
  1623
+    if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):
1624 1624
         pass
1625 1625
     else:
1626 1626
         raise validators.ValidationError, "%s with this %s already exists for the given %s." % \
@@ -1646,7 +1646,7 @@ def manipulator_validator_unique_for_date(from_field, date_field, opts, lookup_t
1646 1646
     except ObjectDoesNotExist:
1647 1647
         return
1648 1648
     else:
1649  
-        if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.column) == getattr(old_obj, opts.pk.column):
  1649
+        if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):
1650 1650
             pass
1651 1651
         else:
1652 1652
             format_string = (lookup_type == 'date') and '%B %d, %Y' or '%B %Y'
35  django/core/meta/fields.py
@@ -55,10 +55,26 @@ def manipulator_validator_unique(f, opts, self, field_data, all_data):
55 55
         old_obj = opts.get_model_module().get_object(**{'%s__%s' % (f.name, lookup_type): field_data})
56 56
     except ObjectDoesNotExist:
57 57
         return
58  
-    if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.column) == getattr(old_obj, opts.pk.column):
  58
+    if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):
59 59
         return
60 60
     raise validators.ValidationError, "%s with this %s already exists." % (capfirst(opts.verbose_name), f.verbose_name)
61 61
 
  62
+
  63
+# A guide to Field parameters:
  64
+#
  65
+#   * name:      The name of the field specifed in the model.
  66
+#   * attname:   The attribute to use on the model object. This is the same as
  67
+#                "name", except in the case of ForeignKeys, where "_id" is
  68
+#                appended.
  69
+#   * db_column: The db_column specified in the model (or None).
  70
+#   * column:    The database column for this field. This is the same as
  71
+#                "attname", except if db_column is specified.
  72
+#
  73
+# Code that introspects values, or does other dynamic things, should use
  74
+# attname. For example, this gets the primary key value of object "obj":
  75
+#
  76
+#     getattr(obj, opts.pk.attname)
  77
+
62 78
 class Field(object):
63 79
 
64 80
     # Designates whether empty strings fundamentally are allowed at the
@@ -110,19 +126,20 @@ def __init__(self, verbose_name=None, name=None, primary_key=False,
110 126
         self.creation_counter = Field.creation_counter
111 127
         Field.creation_counter += 1
112 128
 
113  
-        # Set the name of the database column.
114  
-        self.column = self.get_db_column()
  129
+        self.attname, self.column = self.get_attname_column()
115 130
 
116 131
     def set_name(self, name):
117 132
         self.name = name
118 133
         self.verbose_name = self.verbose_name or name.replace('_', ' ')
119  
-        self.column = self.get_db_column()
  134
+        self.attname, self.column = self.get_attname_column()
120 135
 
121  
-    def get_db_column(self):
122  
-        if self.db_column: return self.db_column
  136
+    def get_attname_column(self):
123 137
         if isinstance(self.rel, ManyToOne):
124  
-            return '%s_id' % self.name
125  
-        return self.name
  138
+            attname = '%s_id' % self.name
  139
+        else:
  140
+            attname = self.name
  141
+        column = self.db_column or attname
  142
+        return attname, column
126 143
 
127 144
     def get_cache_name(self):
128 145
         return '_%s_cache' % self.name
@@ -277,7 +294,7 @@ def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
277 294
         if self.choices:
278 295
             return first_choice + list(self.choices)
279 296
         rel_obj = self.rel.to
280  
-        return first_choice + [(getattr(x, rel_obj.pk.column), repr(x)) for x in rel_obj.get_model_module().get_list(**self.rel.limit_choices_to)]
  297
+        return first_choice + [(getattr(x, rel_obj.pk.attname), repr(x)) for x in rel_obj.get_model_module().get_list(**self.rel.limit_choices_to)]
281 298
 
282 299
 class AutoField(Field):
283 300
     empty_strings_allowed = False
4  django/models/auth.py
@@ -13,7 +13,7 @@ class META:
13 13
         ordering = ('package', 'codename')
14 14
 
15 15
     def __repr__(self):
16  
-        return "%s | %s" % (self.package, self.name)
  16
+        return "%s | %s" % (self.package_id, self.name)
17 17
 
18 18
 class Group(meta.Model):
19 19
     name = meta.CharField(_('name'), maxlength=80, unique=True)
@@ -103,7 +103,7 @@ def get_group_permissions(self):
103 103
     def get_all_permissions(self):
104 104
         if not hasattr(self, '_perm_cache'):
105 105
             import sets
106  
-            self._perm_cache = sets.Set(["%s.%s" % (p.package, p.codename) for p in self.get_permission_list()])
  106
+            self._perm_cache = sets.Set(["%s.%s" % (p.package_id, p.codename) for p in self.get_permission_list()])
107 107
             self._perm_cache.update(self.get_group_permissions())
108 108
         return self._perm_cache
109 109
 
4  django/models/core.py
@@ -48,11 +48,11 @@ class META:
48 48
         unique_together = (('package', 'python_module_name'),)
49 49
 
50 50
     def __repr__(self):
51  
-        return "%s | %s" % (self.package, self.name)
  51
+        return "%s | %s" % (self.package_id, self.name)
52 52
 
53 53
     def get_model_module(self):
54 54
         "Returns the Python model module for accessing this type of content."
55  
-        return __import__('django.models.%s.%s' % (self.package, self.python_module_name), '', '', [''])
  55
+        return __import__('django.models.%s.%s' % (self.package_id, self.python_module_name), '', '', [''])
56 56
 
57 57
     def get_object_for_this_type(self, **kwargs):
58 58
         """

0 notes on commit 2ef937d

Please sign in to comment.
Something went wrong with that request. Please try again.