0

I understand that you can implement a many to many relationship in Flask Sqlalchemy like the following answer I've found for another question

ItemDetail = Table('ItemDetail',
    Column('id', Integer, primary_key=True),
    Column('itemId', Integer, ForeignKey('Item.id')),
    Column('detailId', Integer, ForeignKey('Detail.id')),
    Column('endDate', Date))

class Item(Base):
    __tablename__ = 'Item'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    description = Column(Text)
    details = relationship('Detail', secondary=ItemDetail, backref='Item')

class Detail(Base):
    __tablename__ = 'Detail'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    value = Column(String)
    items = relationship('Item', secondary=ItemDetail, backref='Detail')

I would like to know the best practice to implement this relationship without any fancy object relational models (ORMs).

So far, I've come up with this:

from typing import List
import datetime
# two classes that I would like to relate
class Foo:
    all_ = []
    def __init__(self, name: str):
        self.name = name
        type(self).all_.append(self)

    def foobars(self):
        return [foobar for foobar in FooBar.all_ if self in foobar.foo]

class Bar:
all_ = []
    def __init__(self, name: str):
        self.name = name
        type(self).all_.append(self)

    def foobars(self):
        return [foobar for foobar in FooBar.all_ if self in foobar.bar]
        

class FooBar:
    all_ = []
    def __init__(self, foo: List[Foo], bar: List[Bar], timestamp: datetime.datetime, details: str):
        self.foo = foo
        self.bar = bar
        self.details = details
        self.timestamp - timestamp
        type(self).all_.append(self)

0 Answers0