Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.
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
41 changes: 41 additions & 0 deletions docs/relationships.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,44 @@ A database driver exception will be raised.

This will set referencing objects `ForeignKey` column to `NULL`.
The `ForeignKey` defined here should also have `allow_null=True`.


## OneToOne

Creating a `OneToOne` relationship between models, this is basically
the same as `ForeignKey` but it uses `unique=True` on the ForeignKey column:

```python
class Profile(orm.Model):
registry = models
fields = {
"id": orm.Integer(primary_key=True),
"website": orm.String(max_length=100),
}


class Person(orm.Model):
registry = models
fields = {
"id": orm.Integer(primary_key=True),
"email": orm.String(max_length=100),
"profile": orm.OneToOne(Profile),
}
```

You can create a `Profile` and `Person` instance:

```python
profile = await Profile.objects.create(website="https://encode.io")
await Person.objects.create(email="[email protected]", profile=profile)
```

Now creating another `Person` using the same `profile` will fail
and will raise an exception:

```python
await Person.objects.create(email="[email protected]", profile=profile)
```

`OneToOne` accepts the same `on_delete` parameters as `ForeignKey` which is
described [here](#foreignkey-constraints).
4 changes: 3 additions & 1 deletion orm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
Float,
ForeignKey,
Integer,
OneToOne,
String,
Text,
Time,
Expand All @@ -32,13 +33,14 @@
"Decimal",
"Enum",
"Float",
"ForeignKey",
"Integer",
"JSON",
"OneToOne",
"String",
"Text",
"Time",
"UUID",
"ForeignKey",
"Model",
"ModelRegistry",
]
24 changes: 22 additions & 2 deletions orm/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,7 @@ def get_column(self, name: str) -> sqlalchemy.Column:
column_type = to_field.get_column_type()
constraints = [
sqlalchemy.schema.ForeignKey(
f"{target.tablename}.{target.pkname}",
ondelete=self.on_delete,
f"{target.tablename}.{target.pkname}", ondelete=self.on_delete
)
]
return sqlalchemy.Column(
Expand All @@ -181,6 +180,27 @@ def expand_relationship(self, value):
return target(pk=value)


class OneToOne(ForeignKey):
def get_column(self, name: str) -> sqlalchemy.Column:
target = self.target
to_field = target.fields[target.pkname]

column_type = to_field.get_column_type()
constraints = [
sqlalchemy.schema.ForeignKey(
f"{target.tablename}.{target.pkname}", ondelete=self.on_delete
),
]

return sqlalchemy.Column(
name,
column_type,
*constraints,
nullable=self.allow_null,
unique=True,
)


class Enum(ModelField):
def __init__(self, enum, **kwargs):
super().__init__(**kwargs)
Expand Down
40 changes: 40 additions & 0 deletions tests/test_foreignkey.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import sqlite3

import asyncpg
import databases
import pymysql
Expand Down Expand Up @@ -56,6 +58,23 @@ class Member(orm.Model):
}


class Profile(orm.Model):
registry = models
fields = {
"id": orm.Integer(primary_key=True),
"website": orm.String(max_length=100),
}


class Person(orm.Model):
registry = models
fields = {
"id": orm.Integer(primary_key=True),
"email": orm.String(max_length=100),
"profile": orm.OneToOne(Profile),
}


@pytest.fixture(autouse=True, scope="module")
def create_test_database():
models.create_all()
Expand Down Expand Up @@ -229,3 +248,24 @@ async def test_on_delete_set_null():

member = await Member.objects.first()
assert member.team.pk is None


async def test_one_to_one_crud():
profile = await Profile.objects.create(website="https://encode.io")
await Person.objects.create(email="[email protected]", profile=profile)

person = await Person.objects.get(email="[email protected]")
assert person.profile.pk == profile.pk
assert not hasattr(person.profile, "website")

await person.profile.load()
assert person.profile.website == "https://encode.io"

exceptions = (
asyncpg.exceptions.UniqueViolationError,
pymysql.err.IntegrityError,
sqlite3.IntegrityError,
)

with pytest.raises(exceptions):
await Person.objects.create(email="[email protected]", profile=profile)