+
Skip to content

SQLAlchemy filter operators #130

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 5 commits into from
Nov 4, 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: 17 additions & 0 deletions docs/making_queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ notes = await Note.objects.exclude(completed=False).all()

### .filter()

#### Django-style lookup

To filter instances:

```python
Expand All @@ -69,6 +71,21 @@ notes = await Note.objects.filter(text__icontains="mum").all()
notes = await Note.objects.filter(id__in=[1, 2, 3]).all()
```

#### SQLAlchemy filter operators

The `filter` method also accepts SQLAlchemy filter operators:

```python
notes = await Note.objects.filter(Note.columns.text.contains("mum")).all()

notes = await Note.objects.filter(Note.columns.id.in_([1, 2, 3])).all()
```

Here `Note.columns` refers to the columns of the underlying SQLAlchemy table.

!!! note
Note that `Note.columns` returns SQLAlchemy table columns, whereas `Note.fields` returns `orm` fields.

### .limit()

To limit number of results:
Expand Down
28 changes: 24 additions & 4 deletions orm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ def table(cls):
cls._table = cls.build_table()
return cls._table

@property
def columns(cls) -> sqlalchemy.sql.ColumnCollection:
return cls._table.columns


class QuerySet:
ESCAPE_CHARACTERS = ["%", "_"]
Expand Down Expand Up @@ -171,11 +175,27 @@ def build_select_expression(self):

return expr

def filter(self, **kwargs):
return self._filter_query(**kwargs)
def filter(
self,
clause: typing.Optional[sqlalchemy.sql.expression.BinaryExpression] = None,
**kwargs: typing.Any,
):
if clause is not None:
self.filter_clauses.append(clause)
return self
else:
return self._filter_query(**kwargs)

def exclude(self, **kwargs):
return self._filter_query(_exclude=True, **kwargs)
def exclude(
self,
clause: typing.Optional[sqlalchemy.sql.expression.BinaryExpression] = None,
**kwargs: typing.Any,
):
if clause is not None:
self.filter_clauses.append(clause)
return self
else:
return self._filter_query(_exclude=True, **kwargs)

def _filter_query(self, _exclude: bool = False, **kwargs):
clauses = []
Expand Down
21 changes: 21 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,24 @@ async def test_model_update_or_create():
assert created is False
assert user.name == "Tom"
assert user.language == "English"


async def test_model_sqlalchemy_filter_operators():
user = await User.objects.create(name="George")

assert user == await User.objects.filter(User.columns.name == "George").get()
assert user == await User.objects.filter(User.columns.name.is_not(None)).get()
assert (
user
== await User.objects.filter(User.columns.name.startswith("G"))
.filter(User.columns.name.endswith("e"))
.get()
)

assert user == await User.objects.exclude(User.columns.name != "Jack").get()

shirt = await Product.objects.create(name="100%-Cotton", rating=3)
assert (
shirt
== await Product.objects.filter(Product.columns.name.contains("Cotton")).get()
)
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载