+
Skip to content

queryset-level update method #112

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 1 commit into from
Sep 22, 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
17 changes: 12 additions & 5 deletions docs/making_queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ It's not very common, but to delete all rows in a table:
await Note.objects.delete()
```

You can also call delete on a queried instance:
You can also call `.delete()` on a queried instance:

```python
note = await Note.objects.first()
Expand Down Expand Up @@ -182,16 +182,23 @@ note = await Note.objects.get(id=1)

### .update()

`.update()` method is defined on model instances.
You need to query to get a `Note` instance first:
You can update instances by calling `.update()` on a queryset:

```python
note = await Note.objects.first()
await Note.objects.filter(completed=True).update(completed=False)
```

Then update the field(s):
It's not very common, but to update all rows in a table:

```python
await Note.objects.update(completed=False)
```

You can also call `.update()` on a queried instance:

```python
note = await Note.objects.first()

await note.update(completed=True)
```

Expand Down
24 changes: 18 additions & 6 deletions orm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,23 @@ async def delete(self) -> None:
for filter_clause in self.filter_clauses:
expr = expr.where(filter_clause)

return await self.database.execute(expr)
await self.database.execute(expr)

async def update(self, **kwargs) -> None:
fields = {
key: field.validator
for key, field in self.model_cls.fields.items()
if key in kwargs
}
validator = typesystem.Schema(fields=fields)
kwargs = validator.validate(kwargs)

expr = self.table.update().values(**kwargs)

for filter_clause in self.filter_clauses:
expr = expr.where(filter_clause)

await self.database.execute(expr)

async def get_or_create(self, **kwargs) -> typing.Tuple[typing.Any, bool]:
try:
Expand Down Expand Up @@ -459,19 +475,15 @@ def table(self) -> sqlalchemy.Table:
return self.__class__.table

async def update(self, **kwargs):
# Validate the keyword arguments.
fields = {
key: field.validator for key, field in self.fields.items() if key in kwargs
}
validator = typesystem.Schema(fields=fields)
kwargs = validator.validate(kwargs)

# Build the update expression.
pk_column = getattr(self.table.c, self.pkname)
expr = self.table.update()
expr = expr.values(**kwargs).where(pk_column == self.pk)
expr = self.table.update().values(**kwargs).where(pk_column == self.pk)

# Perform the update.
await self.database.execute(expr)

# Update the model instance.
Expand Down
10 changes: 10 additions & 0 deletions tests/test_foreignkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,13 @@ async def test_queryset_delete_with_fk():
await Track.objects.filter(album=malibu).delete()
assert await Track.objects.filter(album=malibu).count() == 0
assert await Track.objects.filter(album=wall).count() == 1


async def test_queryset_update_with_fk():
malibu = await Album.objects.create(name="Malibu")
wall = await Album.objects.create(name="The Wall")
await Track.objects.create(album=malibu, title="The Bird", position=1)

await Track.objects.filter(album=malibu).update(album=wall)
assert await Track.objects.filter(album=malibu).count() == 0
assert await Track.objects.filter(album=wall).count() == 1
14 changes: 14 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,17 @@ async def test_queryset_delete():

await Product.objects.delete()
assert await Product.objects.count() == 0


async def test_queryset_update():
shirt = await Product.objects.create(name="Shirt", rating=5)
tie = await Product.objects.create(name="Tie", rating=5)

await Product.objects.filter(pk=shirt.id).update(rating=3)
shirt = await Product.objects.get(pk=shirt.id)
assert shirt.rating == 3
assert await Product.objects.get(pk=tie.id) == tie

await Product.objects.update(rating=3)
tie = await Product.objects.get(pk=tie.id)
assert tie.rating == 3
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载