ForeignKey & JOINs
ForeignKey & JOINs
Section titled “ForeignKey & JOINs”PyGo provides automatic foreign key relationship handling with compile-time JOIN generation. Foreign keys are defined in the .pgo DSL and the transpiler generates idiomatic Go and Python code with proper SQL JOIN support.
Defining Relationships
Section titled “Defining Relationships”One-to-Many (ForeignKey)
Section titled “One-to-Many (ForeignKey)”model Author: id: UUID name: String email: Email
model Post: title: String content: String author: ForeignKey[User] author_id: UUIDExplicit Foreign Key Declaration
Section titled “Explicit Foreign Key Declaration”foreignKey user_id -> UserThis generates a get_user() method that fetches the related User record.
Generated Code
Section titled “Generated Code”Python (gen_py.py)
Section titled “Python (gen_py.py)”class Post(BaseModel): title: str content: str author_id: str author: User # ForeignKey field
def get_user(self) -> User: return User.find(self.author_id)Go (gen_go.go)
Section titled “Go (gen_go.go)”type Post struct { Title string Content string AuthorID string Author User}
func (p *Post) GetUser() *User { return UserFind(p.AuthorID)}Querying with JOINs
Section titled “Querying with JOINs”PyGo automatically generates JOIN queries when you access related models:
# Get author for a post (single query, JOIN)post = Post.find(id)author = post.get_user()Foreign Key Options
Section titled “Foreign Key Options”CASCADE Delete
Section titled “CASCADE Delete”model Post: title: String user: ForeignKey[User] # Default: protectMultiple Foreign Keys
Section titled “Multiple Foreign Keys”model Comment: content: String author_id: UUID post_id: UUID author: ForeignKey[User] post: ForeignKey[Post]Many-to-Many Relationships
Section titled “Many-to-Many Relationships”model Tag: name: String
model Article: title: String content: String tags: Array[Tag]Reverse Relations
Section titled “Reverse Relations”Access reverse relationships automatically:
author = Author.find(id)# Get all posts by this authorposts = Post.filter(author_id=author.id)Database Schema
Section titled “Database Schema”CREATE TABLE author ( id UUID PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL);
CREATE TABLE post ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, content TEXT NOT NULL, author_id UUID NOT NULL, FOREIGN KEY (author_id) REFERENCES author(id) ON DELETE CASCADE);Performance Considerations
Section titled “Performance Considerations”- Use
filter()with foreign key fields for indexed lookups - JOINs are generated automatically when using
get_<relation>()methods - Consider denormalization for frequently accessed relationships