Skip to content

Commit 290c6d0

Browse files
authored
Merge pull request #68 from SoprisApps/renamed-column-fixes
Renamed column fixes
2 parents 6d1269f + e0eb6b2 commit 290c6d0

File tree

3 files changed

+34
-10
lines changed

3 files changed

+34
-10
lines changed

psqlextra/manager/manager.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff 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

tests/test_insert.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff 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

tox.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@ deps =
99
setenv =
1010
DJANGO_SETTINGS_MODULE=settings
1111
passenv = DATABASE_URL
12-
commands = python -m pytest --cov=psqlextra
12+
commands = python -m pytest --cov=psqlextra --cov-report=term-missing

0 commit comments

Comments
 (0)