File tree Expand file tree Collapse file tree 3 files changed +34
-10
lines changed
Expand file tree Collapse file tree 3 files changed +34
-10
lines changed Original file line number Diff line number Diff line change @@ -218,20 +218,20 @@ def insert_and_get(self, **fields):
218218
219219 columns = rows [0 ]
220220
221- # get a list of columns that are officially part of the model
222- model_columns = [
223- field . column
224- for field in self .model ._meta .local_concrete_fields
225- ]
221+ # get a list of columns that are officially part of the model and preserve the fact that the attribute name
222+ # might be different than the database column name
223+ model_columns = {}
224+ for field in self .model ._meta .local_concrete_fields :
225+ model_columns [ field . column ] = field . attname
226226
227227 # strip out any columns/fields returned by the db that
228228 # are not present in the model
229229 model_init_fields = {}
230230 for column_name , column_value in columns .items ():
231- if column_name not in model_columns :
232- continue
233-
234- model_init_fields [ column_name ] = column_value
231+ try :
232+ model_init_fields [ model_columns [ column_name ]] = column_value
233+ except KeyError :
234+ pass
235235
236236 return self .model (** model_init_fields )
237237
Original file line number Diff line number Diff line change @@ -98,3 +98,27 @@ def test_insert_on_conflict_explicit_pk():
9898 assert obj1 .pk == 'the-object'
9999 assert obj1 .name == 'the-object'
100100 assert obj1 .cookies == 'some-cookies'
101+
102+
103+ def test_insert_with_different_column_name ():
104+ """Tests whether inserts works when the primary key is explicitly specified."""
105+
106+ model = get_fake_model ({
107+ 'name' : models .CharField (max_length = 255 , primary_key = True ),
108+ 'cookies' : models .CharField (max_length = 255 , null = True , db_column = 'brownies' ),
109+ })
110+
111+ cookie_string = 'these-are-brownies'
112+
113+ results = model .objects \
114+ .on_conflict (['name' ], ConflictAction .NOTHING ) \
115+ .insert_and_get (
116+ name = 'the-object' ,
117+ cookies = cookie_string
118+ )
119+
120+ assert results is not None
121+ assert results .cookies == cookie_string
122+
123+ obj1 = model .objects .get ()
124+ assert obj1 .cookies == cookie_string
Original file line number Diff line number Diff line change 99setenv =
1010 DJANGO_SETTINGS_MODULE =settings
1111passenv = DATABASE_URL
12- commands = python -m pytest --cov =psqlextra
12+ commands = python -m pytest --cov =psqlextra -- cov-report =term-missing
You can’t perform that action at this time.
0 commit comments