Skip to content

Commit 3218432

Browse files
add objects get method (piccolo-orm#183)
* add simple get method * update docs * minor tweak to docs - mention ``None`` is returned if ``get`` finds no match Co-authored-by: Daniel Townsend <[email protected]>
1 parent 1b645cb commit 3218432

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

docs/src/piccolo/query_types/objects.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ To get certain rows:
2828
>>> Band.objects().where(Band.name == 'Pythonistas').run_sync()
2929
[<Band: 1>]
3030
31+
To get a single row (or ``None`` if it doesn't exist):
32+
33+
.. code-block:: python
34+
35+
>>> Band.objects().get(Band.name == 'Pythonistas').run_sync()
36+
<Band: 1>
37+
3138
To get the first row:
3239

3340
.. code-block:: python

piccolo/query/methods/objects.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class GetOrCreate:
3030
defaults: t.Dict[t.Union[Column, str], t.Any]
3131

3232
async def run(self):
33-
instance = await self.query.where(self.where).first().run()
33+
instance = await self.query.get(self.where).run()
3434
if instance:
3535
return instance
3636

@@ -99,6 +99,11 @@ def first(self) -> Objects:
9999
self.limit_delegate.first()
100100
return self
101101

102+
def get(self, where: Combinable) -> Objects:
103+
self.where_delegate.where(where)
104+
self.limit_delegate.first()
105+
return self
106+
102107
def offset(self, number: int) -> Objects:
103108
self.offset_delegate.offset(number)
104109
return self

tests/table/test_objects.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,13 @@ def test_offset_sqlite(self):
6060
[i.name for i in response], ["Pythonistas", "Rustaceans"]
6161
)
6262

63+
def test_get(self):
64+
self.insert_row()
65+
66+
band = Band.objects().get(Band.name == "Pythonistas").run_sync()
67+
68+
self.assertTrue(band.name == "Pythonistas")
69+
6370
def test_get_or_create(self):
6471
Band.objects().get_or_create(
6572
Band.name == "Pink Floyd", defaults={"popularity": 100}

0 commit comments

Comments
 (0)