OneToOne
OneToOne is a foreign key where each related model has at most one model pointing
back at it. It takes the same arguments as ForeignKey (name,
related_name, to_field, db_constraint, ondelete, primary_key, ...).
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
-
The foreign key column is
UNIQUE, so the database rejects a second profile for the same user. AOneToOnethat is the primary key (the shared primary key pattern) is unique already:Python 1 2 3 4 5
class Passport(ormar.Model): ormar_config = base_ormar_config.copy(tablename="passports") user: User = ormar.OneToOne(User, primary_key=True, related_name="passport") number: str = ormar.String(max_length=20) -
The reverse side holds one model or
None, not a list. Its default name is the model name without a trailings(user.profile).
| Python | |
|---|---|
1 2 3 4 5 | |
- The reverse side has no queryset proxy (there is nothing to filter); load it with
select_related/prefetch_related. - Assigning on the reverse side (
user.profile = profile) links both models in memory; save the profile to store the link. - Assigning a new value on either side unlinks the model it replaced: after
user.profile = newthe old profile'suserisNone, and afterprofile.user = bobthe previous user'sprofileisNone.user.profile = Noneunlinks both models. Save the changed models to store it. - Like the reverse side of a
ForeignKey, the reverse side holds a weak reference: if the profile is not referenced anywhere else,user.profilereadsNoneagain.