Skip to content

Instantly share code, notes, and snippets.

@ra0x3
Created March 4, 2020 05:08
Show Gist options
  • Save ra0x3/a29f09b95e60e7e36777e31ec2f2610d to your computer and use it in GitHub Desktop.
Save ra0x3/a29f09b95e60e7e36777e31ec2f2610d to your computer and use it in GitHub Desktop.
A sample messages model in peewee
from peewee import (
BaseModel,
ForeignKeyField,
TextField,
IntegerField,
DateTimeField,
CharField
)
from peewee_extensions import (
Relationship,
Through,
Direct,
ModelRelationship
)
# Conversations model
class Conversations(BaseModel):
class Meta:
table_name = "conversations"
database = db
relations = ModelRelationship(
data={
"messages": Relationship(
"through",
Through(
"id",
"users_conversations",
"conversation_id",
"user_conversation_id",
),
),
}
)
# Messages model
class Messages(BaseModel):
class Meta:
table_name = "messages"
database = db # a predefined database object (just as in the docs)
protected_fields = ["read_at", "_text"]
relations = ModelRelationship(
data={
"conversations": Relationship(
"through",
Through(
"user_conversation_id",
"users_conversations",
"conversation_id",
"id",
),
),
"users": Relationship(
"through",
Through(
"user_conversation_id", "users_conversations", "user_id", "id"
),
),
}
)
user_conversation = ForeignKeyField(UsersConversations, field="id")
_text = TextField()
sent_at = DateTimeField(null=False)
read = BooleanField(default=False)
transaction = ForeignKeyField(Transactions, field="id", null=True)
_read_at = CharField(null=True)
@property
def text(self):
return self._text
@text.setter
def text(self, value):
self._text = value
@property
def read_at(self):
return float(self._read_at)
@read_at.setter
def read_at(self, value):
self._read_at = str(value)
# users_conversations through table
class UsersConversations(BaseModel):
class Meta:
table_name = "users_conversations"
database = db
indexes = ((("user_id", "conversation_id"), True),)
user = ForeignKeyField(Users, field="id")
conversation = ForeignKeyField(Conversations, field="id")
# users model
class Users(BaseModel):
class Meta:
table_name = "users"
database = db
protected_fields = [
"name",
"phone",
]
secret_fields = [
"salt",
"secret_hash",
"twofactor_token",
]
relations = ModelRelationship(
data={
"transactions": Relationship("direct", Direct("id", "user_id")),
"messages": Relationship(
"through",
Through(
"id",
"users_conversations",
"user_id",
"users_conversations_id",
),
),
}
)
_name = CharField(null=True)
_phone = CharField()
_salt = IntegerField(null=True)
_secret_hash = CharField(null=True)
_twofactor_token = CharField(null=True)
first_name = CharField(null=False)
last_login = CharField(default=dt.datetime.now())
last_name = CharField(null=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment