aurweb/aurweb/models/tu_vote.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

40 lines
1.4 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.tu_voteinfo import TUVoteInfo as _TUVoteInfo
from aurweb.models.user import User as _User
class TUVote(Base):
__tablename__ = "TU_Votes"
VoteID = Column(Integer, ForeignKey("TU_VoteInfo.ID", ondelete="CASCADE"),
nullable=False)
VoteInfo = relationship(
_TUVoteInfo, backref=backref("tu_votes", lazy="dynamic"),
foreign_keys=[VoteID])
UserID = Column(Integer, ForeignKey("Users.ID", ondelete="CASCADE"),
nullable=False)
User = relationship(
_User, backref=backref("tu_votes", lazy="dynamic"),
foreign_keys=[UserID])
__mapper_args__ = {"primary_key": [VoteID, UserID]}
def __init__(self, **kwargs):
super().__init__(**kwargs)
if not self.VoteInfo and not self.VoteID:
raise IntegrityError(
statement="Foreign key VoteID cannot be null.",
orig="TU_Votes.VoteID",
params=("NULL"))
if not self.User and not self.UserID:
raise IntegrityError(
statement="Foreign key UserID cannot be null.",
orig="TU_Votes.UserID",
params=("NULL"))