Skip to content

Commit 119c920

Browse files
tr11fantix
authored andcommitted
Allow for primary keys with different names from the database columns.
Fixes #599.
1 parent f76a493 commit 119c920

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/gino/crud.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,7 @@ async def get(cls, ident, bind=None, timeout=DEFAULT):
533533
try:
534534
val = ident_[i]
535535
except KeyError:
536-
val = ident_[c.name]
536+
val = ident_[cls._column_name_map.invert_get(c.name)]
537537
clause = clause.where(c == val)
538538
if timeout is not DEFAULT:
539539
clause = clause.execution_options(timeout=timeout)
@@ -579,7 +579,7 @@ def lookup(self):
579579
"""
580580
exps = []
581581
for c in self.__table__.primary_key.columns:
582-
exps.append(c == getattr(self, c.name))
582+
exps.append(c == getattr(self, self._column_name_map.invert_get(c.name)))
583583
if exps:
584584
return sa.and_(*exps)
585585
else:

tests/test_crud.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,3 +285,37 @@ class Game(db.Model):
285285
assert await Game.select("channel_id").gino.all() == [("X",), ("Z",)]
286286
finally:
287287
await Game.gino.drop()
288+
289+
290+
async def test_lookup_custom_name(bind):
291+
from gino.exceptions import NoSuchRowError
292+
293+
class ModelWithCustomColumnNames(db.Model):
294+
__tablename__ = 'gino_test_custom_column_names'
295+
296+
id = db.Column('other', db.Integer(), primary_key=True)
297+
field = db.Column(db.Text())
298+
299+
await ModelWithCustomColumnNames.gino.create()
300+
301+
try:
302+
# create
303+
m1 = await ModelWithCustomColumnNames.create(id=1, field='A')
304+
m2 = await ModelWithCustomColumnNames.create(id=2, field='B')
305+
306+
# update
307+
uq = m1.update(field='C')
308+
await uq.apply()
309+
310+
# lookup
311+
assert set(tuple(x) for x in await ModelWithCustomColumnNames.select('id').gino.all()) == {(1,), (2,)}
312+
assert (await ModelWithCustomColumnNames.get(2)).field == "B"
313+
assert (await ModelWithCustomColumnNames.get(1)).field == "C"
314+
assert await ModelWithCustomColumnNames.get(3) is None
315+
316+
# delete
317+
assert (await ModelWithCustomColumnNames.delete.where(ModelWithCustomColumnNames.id == 3).gino.status())[0][-1] == '0'
318+
assert (await ModelWithCustomColumnNames.delete.where(ModelWithCustomColumnNames.id == 2).gino.status())[0][-1] == '1'
319+
assert set(tuple(x) for x in await ModelWithCustomColumnNames.select('id').gino.all()) == {(1,)}
320+
finally:
321+
await ModelWithCustomColumnNames.gino.drop()

0 commit comments

Comments
 (0)