Hackforge Academy

Category: python

database relationships and crud operations

Published on 30 Sep 2026

Explanation

One-to-many relationships represent cases such as one user having many orders.

Code:

User
  |
  +---- Order 1
  +---- Order 2
  +---- Order 3

Explanation

Define a foreign key to connect the Order table with the User table.

Code:

class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(
        db.Integer,
        db.ForeignKey('user.id')
    )

Explanation

Create a relationship between User and Order models using SQLAlchemy.

Code:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    orders = db.relationship('Order', backref='user')

Explanation

Update an existing database record and commit the transaction.

Code:

user = User.query.get(101)
user.name = 'New Name'

db.session.commit()

Explanation

Delete an existing database record using the SQLAlchemy session.

Code:

user = User.query.get(101)

if user:
    db.session.delete(user)
    db.session.commit()

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community