docs
Django
Related Table

In Django, related tables are often managed using model relationships like ForeignKey, OneToOneField, and ManyToManyField. These relationships allow you to link one model to another, representing real-world relationships between entities in your database.

Example: E-commerce Application with Related Tables

Let's consider an example where we have three models: Product, Category, and Order.

  1. Product: Represents the items for sale.
  2. Category: Represents categories of products.
  3. Order: Represents an order placed by a customer.

Models

from django.db import models
 
# Category Model
class Category(models.Model):
    name = models.CharField(max_length=100)
 
    def __str__(self):
        return self.name
 
# Product Model
class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
 
    def __str__(self):
        return self.name
 
# Order Model
class Order(models.Model):
    products = models.ManyToManyField(Product, related_name='orders')
    order_date = models.DateTimeField(auto_now_add=True)
    total_price = models.DecimalField(max_digits=10, decimal_places=2)
 
    def __str__(self):
        return f"Order {self.id} on {self.order_date}"

Explanation

  1. Category Model:

    • A simple model with a name field.
    • A Category can have multiple Products associated with it.
  2. Product Model:

    • name, description, and price fields describe the product.
    • category: This is a ForeignKey field that creates a many-to-one relationship with the Category model. Each Product is associated with a single Category, but a Category can have many Products. The on_delete=models.CASCADE ensures that if a category is deleted, all associated products are also deleted.
  3. Order Model:

    • products: This is a ManyToManyField that creates a many-to-many relationship with the Product model. An Order can contain multiple Products, and a Product can be part of multiple Orders.
    • order_date and total_price are additional fields to track the order's date and total amount.

Querying Related Data

With these relationships, you can easily query related data.

  • Get all products in a category:
category = Category.objects.get(name='Electronics')
products = category.products.all()  # Access related products via the 'related_name' in ForeignKey
  • Get all orders containing a specific product:
product = Product.objects.get(name='Smartphone')
orders = product.orders.all()  # Access related orders via the 'related_name' in ManyToManyField

Admin Display

In the Django admin, related fields are automatically displayed, allowing you to select related objects.

from django.contrib import admin
from .models import Category, Product, Order
 
admin.site.register(Category)
admin.site.register(Product)
admin.site.register(Order)

This setup effectively manages relationships between tables in Django, making it easy to model real-world entities and their connections in your application.

To search for product details from a category and category details from a product in Django, you can utilize Django's ORM (Object-Relational Mapping) to query related data. Below are examples of how to perform these searches.

1. Search Product Details from a Category

If you have a Category and want to get all the products associated with it, you can do the following:

Example Query

# Get a specific category (e.g., 'Electronics')
category = Category.objects.get(name='Electronics')
 
# Get all products in this category
products = category.products.all()
 
# Loop through the products to get their details
for product in products:
    print(f"Product Name: {product.name}, Description: {product.description}, Price: {product.price}")

2. Search Category Details from a Product

If you have a Product and want to get the category it belongs to, you can do the following:

Example Query

# Get a specific product (e.g., 'Smartphone')
product = Product.objects.get(name='Smartphone')
 
# Get the category of this product
category = product.category
 
# Print the category details
print(f"Category Name: {category.name}")

Putting It Together in a View

You might want to implement these queries in a Django view to display the information on a webpage.

Example View to Get Products from a Category

from django.shortcuts import render, get_object_or_404
from .models import Category
 
def products_by_category(request, category_name):
    category = get_object_or_404(Category, name=category_name)
    products = category.products.all()
    return render(request, 'products_by_category.html', {'category': category, 'products': products})

Example View to Get Category from a Product

from django.shortcuts import render, get_object_or_404
from .models import Product
 
def category_by_product(request, product_name):
    product = get_object_or_404(Product, name=product_name)
    category = product.category
    return render(request, 'category_by_product.html', {'product': product, 'category': category})

Templates Example

products_by_category.html

<h1>Products in Category: {{ category.name }}</h1>
<ul>
    {% for product in products %}
        <li>{{ product.name }} - ${{ product.price }}</li>
    {% endfor %}
</ul>

category_by_product.html

<h1>Category for Product: {{ product.name }}</h1>
<p>Category: {{ category.name }}</p>

Summary

  • To search products from a category: Use category.products.all() to retrieve all products related to a specific category.
  • To search the category from a product: Use product.category to get the category to which a specific product belongs.

These queries leverage Django's ORM to efficiently retrieve related data based on your model relationships.