Hello,
I am new to databases, and would like to know how to best store personal messages in a database (with SQLAlchemy).
Because I wasn't sure, I have tried the following table for PMs
pm_table = Table('personal_message', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('from_id', Integer, ForeignKey('user.id')),
Column('to_id', Integer, ForeignKey('user.id')),
Column('message', Text),
Column('sent_at', DateTime)
)
and then this is mapped
session.mapper(User, user_table, properties={
'messages_sent': relation(PM, backref='sender'),
'messages_received': relation(PM, backref='receiver')
})
I get the following error message:
Could not determine join condition between parent/child tables on relation User.messages_sent. Specify a 'primaryjoin' expression. If this is a many-to-many relation, 'secondaryjoin' is needed as well.
From what I understand so far, this is a one-to-many relationship, but with two foreign keys to the same class. Is this even the right approach or should I have two tables, messages_sent
and messages_received
? Or still something else? Any pointers in the right direction would be very much appreciated.
EDIT:
To clarify, I'm after a good database design pattern to solve this. If somebody can help with SQLAlchemy, that would be great, but by no means necessary.
but the
from_id
-column would be the user-id of the sender, and theto_id
would be the user-id of the reciever?
Exactly.
Your code sample is incomplete.
I tried to omit unnecessary code in this post, seems I went to far. Here are the missing definitions.
class PM(object):
def __init__(self, from_id, to_id, message):
self.from_id = from_id
self.to_id = to_id
self.message = message
self.sent_at = datetime.utcnow()
session.mapper(PM, pm_table)
class User(object):
def __init__(self, username, pwsalt, pwhash, email):
self.username = username
self.pwsalt = pwsalt
self.pwhash = pwhash
self.email = email
self.since = datetime.utcnow()
self.status = 0
user_table = Table('user', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('username', String(20)),
Column('pwsalt', String(32)),
Column('pwhash', String(64)),
Column('email', String(320)),
Column('since', DateTime),
Column('status', SmallInteger)
)