🚀 Day 19: Models & Database in Django As I dive deeper into Django, I explored how data is structured and managed using Models. 👉 In Django, a Model defines the structure of your database. It acts as a bridge between your application and the database. 🔹 What is a Model? A model is a Python class that represents a database table. Each attribute in the class corresponds to a column in the table. 💡 Example: from django.db import models class Student(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() 🔹 Key Concepts: ✔ Fields → Define data types (CharField, IntegerField, etc.) ✔ Migrations → Apply changes to the database ✔ ORM (Object Relational Mapping) → Interact with DB using Python instead of SQL 🔹 Basic Commands: python manage.py makemigrations python manage.py migrate 📌 Why it matters? ✔ Simplifies database operations ✔ Eliminates the need to write raw SQL ✔ Makes applications scalable and maintainable Django’s ORM is one of its most powerful features for backend development. 💡 Good developers don’t just store data they structure it efficiently. 📈 Step by step, building real-world backend expertise. #Django #Python #Database #BackendDevelopment #ORM #WebDevelopment #LearningJourney #FullStack
Django Models & Database Structure
More Relevant Posts
-
As a Django developers don't stop at “it works.” Go further, make it fast, scalable, and production-ready 🚀 Here’s a simple example 👇 Basic query (works, but not optimal): orders = Order.objects.filter(items__product__user=user).distinct() It gets the correct data… But can trigger multiple database queries later (slow performance). Now the professional version 👇 orders = Order.objects.filter( items__product__user=user ).select_related('user').prefetch_related('items__product').distinct() Same result. But way more efficient. Why this matters: Without optimization → multiple database hits With optimization → data fetched once and reused Simple analogy: Without optimization = going to the market 10 times With optimization = buying everything in one trip Use this when you’re: • Looping through querysets • Accessing related data (user, items, products) • Building dashboards or real-world apps Quick tip: select_related → SQL JOIN (ForeignKey, OneToOne) prefetch_related → separate query + Python merge (ManyToMany, reverse FK) If you're learning Django, this is the difference between beginner and professional. Follow for more real-world dev tips 🚀 #Django #Python #WebDevelopment #Backend #Programming #SoftwareEngineering #LinkedIn
To view or add a comment, sign in
-
-
🚀 Understanding Django ORM — The Bridge Between Databases and Python If you're getting started with Django, one of the most powerful features you'll come across is the ORM (Object-Relational Mapping). 🔹 What is ORM? ORM allows you to interact with your database using Python code instead of writing raw SQL queries. It acts as a translator between your database and your application. 🔹 Why use Django ORM? ✔ Write clean, readable Python instead of complex SQL ✔ Faster development with less boilerplate ✔ Built-in protection against SQL injection ✔ Database-agnostic (PostgreSQL, MySQL, SQLite, etc.) 🔹 How it works (as shown in the image): You write Python code using Django models Django ORM converts it into SQL queries The database executes those queries Results are returned as Python objects 🔹 Basic CRUD Operations in Django ORM: 🟢 Create Student.objects.create(name="Ali", age=21) 🔵 Read Student.objects.all() Student.objects.filter(age__gt=20) 🟡 Update student = Student.objects.get(id=1) student.age = 22 student.save() 🔴 Delete student = Student.objects.get(id=1) student.delete() 🔹 Example Comparison: SQL: SELECT * FROM students WHERE age > 20; Django ORM: Student.objects.filter(age__gt=20) 🔥 Powerful Query (Combining Filters, Ordering, and Aggregation): Student.objects.filter(age__gt=20).exclude(name="Ali").order_by("-age") 💡 Final Thought: Django ORM lets developers focus more on application logic rather than database complexity, making development faster, cleaner, and more scalable. #Django #Python #WebDevelopment #ORM #BackendDevelopment #SoftwareEngineering #CRUD
To view or add a comment, sign in
-
-
Day-120,121 📘 Python Full Stack Journey – Django Forms & User Input Handling Today I learned how to handle user input in Django using models and forms — an important step toward building interactive and data-driven applications. 🚀 🎯 What I learned today: 🗄️ Model Creation (Contact Form) Created a Contact model to store user data: Name Email Phone number Applied migrations and registered the model in Django Admin for easy data management 📝 Django ModelForm Created a form using Django’s built-in ModelForm: class BookingContact(forms.ModelForm): class Meta: model = Contact fields = '__all__' Learned how Django automatically generates form fields from models 🌐 Displaying Forms in Templates Rendered forms in HTML using: {{ form }} {{ form.as_p }} for structured layout 📩 Form Submission (POST Method) Used POST method for secure data submission Added {% csrf_token %} for protection Handled form submission in views.py: if request.method == 'POST': form = BookingContact(request.POST) if form.is_valid(): form.save() 🎨 Custom Form Styling Styled individual form fields manually using labels and inputs Learned how to design forms for better user experience This session helped me understand how Django manages forms, validation, and database storage seamlessly — a key step in building real-world web applications. Excited to keep building more interactive features! 💻✨ #Django #Python #FullStackDevelopment #WebDevelopment #Backend #Forms #Database #CodingJourney #LearningToCode #Upskilling #ContinuousLearning
To view or add a comment, sign in
-
-
Django ORM Explained Like a Pro 😎 Still writing raw SQL in Django? 😳 You’re missing the real power ❌ Content: Django ORM makes database work simple + powerful 👇 ⚡ What is Django ORM? → It lets you interact with database using Python → No need to write raw SQL 🔥 Example: ❌ Raw SQL: SELECT * FROM users WHERE age > 18; ✅ Django ORM: users = User.objects.filter(age__gt=18) Simple, clean, readable 🔥 ⚡ Powerful ORM features: 🚀 Filtering data → .filter(), .exclude() 🚀 Relationships → ForeignKey, ManyToMany 🚀 Aggregations → .count(), .sum() 🚀 Query optimization → select_related, prefetch_related ❌ What beginners do: ❌ Use raw queries everywhere ❌ Write complex SQL ✅ What smart devs do: ✅ Use ORM effectively ✅ Write clean queries ✅ Optimize performance Why this matters: Clean queries = better code 💯 Reality: ORM is not slow… Bad usage is 😳 Pro Tip: Learn ORM deeply… It will save you hours ⏳ CTA: Follow me for Django mastery 🚀 Save this post 💾 Comment "ORM" if you learned something 👇 #Django #Python #Backend #ORM #Programming #Developer #Coding #SoftwareEngineer #Tech #WebDevelopment
To view or add a comment, sign in
-
-
📘 Day 89: Django – CRUD Operations (Create & Read) 🔹 What is CRUD? • CRUD = Create, Read, Update, Delete • Allows users (not just admin) to manage data • Core concept in real-world applications 🔸 Create (Employee Registration) 🔹 Model Creation • A model is created to store employee details • Fields include: name, employee ID, phone, email 🔸 Admin Registration • Model is registered so admin can view data 🔸 Form Creation (Frontend) • HTML form is created for user input 🔹 Key Points: • Each input has a name attribute • required ensures fields are not empty • CSRF token is used for security 🔸 Saving Data (Views) Flow: Check if method is POST Fetch data using request.POST Store values in variables Create object of model Assign values to fields Save data 💡 Data submitted by user → stored in database 🔸 Read (Display Data) 🔹 Fetching Data • All records retrieved using: • objects.all() 🔸 Passing to Template • Data is sent using dictionary 🔸 Displaying in HTML Table • Data shown using loop 🔹 Table Structure: • Headers (static) • Rows (dynamic using loop) 💡 Special Feature: • forloop.counter generates serial number 🔸 Real-Time Data • Data entered in form appears instantly in table • Shows connection between frontend & database 🔸 Redirect After Submit • Automatically moves user to another page 🔹 Why? • Better user experience • Avoid duplicate submissions 🔸 Two Ways: • Using URL name (recommended) • Using function name ✨ Today you learned: • CRUD basics (Create & Read) • Connecting HTML form with Django backend • Saving user input into database • Fetching and displaying data dynamically • Using loops in templates • Redirecting after form submission This is the foundation of any dynamic web application where users interact with data 🔥 #Django #CRUD #Python #WebDevelopment #Forms #Database #Day89 #FullStack #CodingJourney
To view or add a comment, sign in
-
💡One small Django detail that can silently break authentication! A lot of beginners assume these 3 methods do the same thing: 1- User.objects.create() 2- User.objects.create_user() 3- User.objects.create_superuser() Actually they don’t. Here’s the real difference: ✅ create() This is the raw ORM method used to create any model object. It simply inserts data into the database. The dangerous part? If you pass a password here, Django stores it as ''plain text'' unless you manually call set_password(). --> That means login will fail because Django expects a hashed password. ✅ create_user() This is the correct method for creating normal authenticated users. It usually: 1- validates required fields 2- hashes the password with set_password() 3- saves the user safely --> It applies any custom business logic from your manager "This should be your default choice for sign-up systems, APIs, and scripts." ✅ create_superuser() This builds on create_user() but also sets the required admin flags: is_staff=True is_superuser=True is_active=True --> This is what allows access to Django admin because of setting is_staff flag to True. 💡Summary: create() = just create a DB row create_user() = create a real login account create_superuser() = create an admin account Understanding this difference early saves hours of debugging “why can’t my user log in?” issues. #Django #Python #WebDevelopment #Backend #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
-
Most Django developers hit the database way more than they need to. I see this pattern constantly in codebases: ❌ The slow way: # N+1 query — hits DB once per order orders = Order.objects.all() for order in orders: print(order.user.name) # separate query every loop This runs 1 + N database queries. With 500 orders, that's 501 queries on a single page load. ✅ The fix — select_related(): # 1 query total using SQL JOIN orders = Order.objects.select_related('user').all() for order in orders: print(order.user.name) # no extra DB hit Use select_related() for ForeignKey / OneToOne fields. Use prefetch_related() for ManyToMany or reverse FK relations. This single change dropped our API response time by 60% on a production endpoint last month. Django's ORM makes it easy to write code that looks clean but silently destroys performance. Always check your query count with Django Debug Toolbar before shipping a new endpoint. What's your go-to Django optimization? Drop it below 👇 #Django #Python #WebDevelopment #FullStackDeveloper #BackendDevelopment #PythonDeveloper #SoftwareEngineering #DjangoTips
To view or add a comment, sign in
-
Most beginners think web development means building everything from scratch… That’s where Django makes things much easier 🚀 Django is a powerful Python web framework that helps you build applications faster, securely, and in an organized way. Instead of worrying about setup and repetitive tasks, Django lets you focus on what actually matters — your idea 💡 🔑 Why Django stands out: ✨ Built-in Admin Panel: Manage your data instantly without creating dashboards from scratch 🗄️ ORM (Object Relational Mapping): Interact with your database using Python instead of complex SQL 🔐 Security First: Protection against common threats like SQL injection & XSS 🧱 Clean Structure (MVT): Keeps your code organized and scalable as your project grows ⚡ Faster Development: Go from idea → working product in less time 💡 In simple terms: Django is not just a framework — it’s a complete toolkit for building real-world applications. If you're starting with backend development in Python, learning Django can give you a strong foundation 📈 smartData Enterprises Inc. #Django #Python #WebDevelopment #Backend #Coding #SoftwareEngineering #smartDataEnterprisesInc
To view or add a comment, sign in
-
🚀 Django Learning Journey – Project Update Recently, I built an Inventory Management System using Django 📦 Here’s what I implemented: ✔ Add, Update & Delete Products (CRUD Operations) ✔ Stock Management & Tracking ✔ Organized Models & Database Design ✔ Django Admin Customization ✔ Clean UI using HTML, CSS & Bootstrap This project helped me understand how real-world systems handle data management and business logic — especially how backend systems track and update inventory efficiently. One key takeaway: 👉 Building CRUD-based systems is the foundation of most real-world applications. 💻 Check out the project here: https://lnkd.in/dyiD3w7d Next step: I’m continuing to strengthen my backend skills and moving deeper into Django REST Framework (DRF) to build scalable APIs. I’m sharing my journey to stay consistent and connect with other developers. #Django #BackendDevelopment #Python #WebDevelopment #LearningInPublic #Projects
To view or add a comment, sign in
-
-
Built a Django automation system that eliminated all manual API data fetching. Here's the full technical breakdown 🧵 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: Daily API → Database sync was done manually. Slow, unreliable, and not scalable. 𝗦𝘁𝗮𝗰𝗸 𝘂𝘀𝗲𝗱: • Django Custom Management Commands • APScheduler (BlockingScheduler + CronTrigger) • Django ORM for database storage 𝗛𝗼𝘄 𝗶𝘁 𝘄𝗼𝗿𝗸𝘀: 1️⃣ Custom Command (management/commands/fetch_generation_data.py) → Calls external API → Parses and validates response → Saves to DB via Django ORM → Run manually: python manage.py fetch_generation_data 2️⃣ Scheduler Command (management/commands/runscheduler.py) → Initializes APScheduler BlockingScheduler → Adds the fetch job with CronTrigger (daily at 12:30 AM) → Runs: python manage.py runscheduler 3️⃣ Database → Job results stored and visible in Django admin panel 𝗪𝗵𝘆 𝗔𝗣𝗦𝗰𝗵𝗲𝗱𝘂𝗹𝗲𝗿 𝗼𝘃𝗲𝗿 𝗖𝗲𝗹𝗲𝗿𝘆? For a single scheduled job with no queue complexity, APScheduler is lighter, simpler to set up, and has zero infrastructure overhead. 𝗥𝗲𝘀𝘂𝗹𝘁: A fully automated, production-ready data pipeline in Django. Building this made me realize how much time developers waste on tasks that code can handle. #Django #Python #APScheduler #Automation #BackendDevelopment #SoftwareEngineering #LearningInPublic #PythonBackend
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development