change(fastapi): unify all model relationship behavior

Now, we allow the direct relationships and their foreign keys to
be set in all of our models. Previously, we constrained this to
direct relationships, and this forced users to perform a query
in most situations to satisfy that requirement. Now, IDs can be
passed directly.

Additionally, this change removes the need for extraneous imports
when users which to use relationships. We now import and use models
directly instead of passing string-references to them.

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-10-16 16:16:44 -07:00
parent 0c37216626
commit 51320ab22a
No known key found for this signature in database
GPG key ID: F7E46DED420788F3
24 changed files with 181 additions and 297 deletions

View file

@ -2,10 +2,9 @@ from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import backref, relationship
import aurweb.models.package_base
import aurweb.models.user
from aurweb.models.declarative import Base
from aurweb.models.package_base import PackageBase as _PackageBase
from aurweb.models.user import User as _User
class PackageNotification(Base):
@ -15,32 +14,29 @@ class PackageNotification(Base):
Integer, ForeignKey("Users.ID", ondelete="CASCADE"),
nullable=False)
User = relationship(
"User", backref=backref("notifications", lazy="dynamic"),
_User, backref=backref("notifications", lazy="dynamic"),
foreign_keys=[UserID])
PackageBaseID = Column(
Integer, ForeignKey("PackageBases.ID", ondelete="CASCADE"),
nullable=False)
PackageBase = relationship(
"PackageBase",
_PackageBase,
backref=backref("notifications", lazy="dynamic"),
foreign_keys=[PackageBaseID])
__mapper_args__ = {"primary_key": [UserID, PackageBaseID]}
def __init__(self,
User: aurweb.models.user.User = None,
PackageBase: aurweb.models.package_base.PackageBase = None,
NotificationTS: int = None):
self.User = User
if not self.User:
def __init__(self, **kwargs):
super().__init__(**kwargs)
if not self.User and not self.UserID:
raise IntegrityError(
statement="Foreign key UserID cannot be null.",
orig="PackageNotifications.UserID",
params=("NULL"))
self.PackageBase = PackageBase
if not self.PackageBase:
if not self.PackageBase and not self.PackageBaseID:
raise IntegrityError(
statement="Foreign key PackageBaseID cannot be null.",
orig="PackageNotifications.PackageBaseID",