+
Skip to content

get_or_create method #106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/making_queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ await Note.objects.order_by("id").limit(1).offset(1).all()
await Note.objects.filter(text__icontains="mum").limit(2).all()
```

#### .exists()

To check if any instances matching the query exist. Returns `True` or `False`.

```python
await Note.objects.filter(completed=True).exists()
```

### Updating instances

`.update()` method is defined on model instances.
Expand Down Expand Up @@ -169,3 +177,16 @@ Then delete the instance:
```python
await note.delete()
```

### Convenience methods

#### get_or_create()

To get an existing instance matching the query, or create a new one.
This will retuurn a tuple of `instance` and `created`.

```python
note, created = await Note.objects.get_or_create(text="Going to car wash")
```

**Note**: Since this is doing a [get()](#get), it can raise `MultipleMatches` exception.
8 changes: 8 additions & 0 deletions orm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,14 @@ async def create(self, **kwargs):
instance.pk = await self.database.execute(expr)
return instance

async def get_or_create(self, **kwargs) -> typing.Tuple[typing.Any, bool]:
try:
instance = await self.get(**kwargs)
return instance, False
except NoMatch:
instance = await self.create(**kwargs)
return instance, True

def _prepare_order_by(self, order_by: str):
reverse = order_by.startswith("-")
order_by = order_by.lstrip("-")
Expand Down
11 changes: 11 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,14 @@ async def test_model_first():
assert await User.objects.first(name="Jane") == jane
assert await User.objects.filter(name="Jane").first() == jane
assert await User.objects.filter(name="Lucy").first() is None


async def test_model_get_or_create():
async with database:
user, created = await User.objects.get_or_create(name="Tom")

assert created is True
assert await User.objects.get(pk=user.id) == user

user, created = await User.objects.get_or_create(name="Tom")
assert created is False
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载