aurweb/aurweb/models/package.py
Kevin Morris 51320ab22a
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>
2021-10-16 16:24:00 -07:00

36 lines
1.1 KiB
Python

from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import backref, relationship
from aurweb.models.declarative import Base
from aurweb.models.package_base import PackageBase as _PackageBase
class Package(Base):
__tablename__ = "Packages"
ID = Column(Integer, primary_key=True)
PackageBaseID = Column(
Integer, ForeignKey("PackageBases.ID", ondelete="CASCADE"),
nullable=False)
PackageBase = relationship(
_PackageBase, backref=backref("packages", lazy="dynamic"),
foreign_keys=[PackageBaseID])
__mapper_args__ = {"primary_key": [ID]}
def __init__(self, **kwargs):
super().__init__(**kwargs)
if not self.PackageBase and not self.PackageBaseID:
raise IntegrityError(
statement="Foreign key PackageBaseID cannot be null.",
orig="Packages.PackageBaseID",
params=("NULL"))
if self.Name is None:
raise IntegrityError(
statement="Column Name cannot be null.",
orig="Packages.Name",
params=("NULL"))