Skip to content

Commit d861bb5

Browse files
authored
added create method (piccolo-orm#245)
* added create method piccolo-orm#238 * removed unnecessary comment * updated Docs
1 parent 5205125 commit d861bb5

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

docs/src/piccolo/query_types/objects.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ Creating objects
5757
>>> band = Band(name="C-Sharps", popularity=100)
5858
>>> band.save().run_sync()
5959
60+
This can also be done like this:
61+
62+
.. code-block:: python
63+
64+
>>> band.objects().create(name="C-Sharps", popularity=100).run_sync()
65+
6066
-------------------------------------------------------------------------------
6167

6268
Updating objects

piccolo/query/methods/objects.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,36 @@ def prefetch(self, *fk_columns) -> GetOrCreate:
8282
return self
8383

8484

85+
@dataclass
86+
class Create:
87+
query: Objects
88+
columns: t.Dict[str, t.Any]
89+
90+
async def run(self):
91+
instance = self.query.table()
92+
93+
for column, value in self.columns.items():
94+
if isinstance(column, str):
95+
column = instance._meta.get_column_by_name(column)
96+
setattr(instance, column._meta.name, value)
97+
98+
await instance.save().run()
99+
100+
instance._was_created = True
101+
102+
return instance
103+
104+
def __await__(self):
105+
"""
106+
If the user doesn't explicity call .run(), proxy to it as a
107+
convenience.
108+
"""
109+
return self.run().__await__()
110+
111+
def run_sync(self):
112+
return run_sync(self.run())
113+
114+
85115
@dataclass
86116
class Objects(Query):
87117
"""
@@ -151,6 +181,9 @@ def get_or_create(
151181
):
152182
return GetOrCreate(query=self, where=where, defaults=defaults)
153183

184+
def create(self, **columns: t.Any):
185+
return Create(query=self, columns=columns)
186+
154187
def order_by(self, *columns: Column, ascending=True) -> Objects:
155188
self.order_by_delegate.order_by(*columns, ascending=ascending)
156189
return self
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from unittest import TestCase
2+
3+
from tests.example_apps.music.tables import Manager
4+
5+
6+
class TestCreate(TestCase):
7+
def setUp(self):
8+
Manager.create_table().run_sync()
9+
10+
def tearDown(self):
11+
Manager.alter().drop_table().run_sync()
12+
13+
def test_create_new(self):
14+
"""
15+
Make sure that creating a new instance works.
16+
"""
17+
Manager.objects().create(name="Maz").run_sync()
18+
19+
names = [i["name"] for i in Manager.select(Manager.name).run_sync()]
20+
self.assertTrue("Maz" in names)

0 commit comments

Comments
 (0)