Django
Models

Django Models - Panduan Lengkap

1. Dasar Model Django

Model adalah representasi database dalam bentuk class Python. Model mendefinisikan struktur dan perilaku data yang disimpan.

Struktur Dasar Model

from django.db import models
 
class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)
 
    def __str__(self):
        return self.name

2. Tipe Field Umum

Text Fields

# Field untuk teks
title = models.CharField(max_length=200)           # Teks pendek
description = models.TextField()                   # Teks panjang
email = models.EmailField()                       # Validasi email
slug = models.SlugField()                         # URL-friendly text

Number Fields

# Field untuk angka
price = models.DecimalField(max_digits=10, decimal_places=2)  # Angka desimal
quantity = models.IntegerField()                              # Bilangan bulat
rating = models.FloatField()                                  # Angka desimal
is_active = models.BooleanField(default=True)                # True/False

Date/Time Fields

# Field untuk tanggal dan waktu
created_at = models.DateTimeField(auto_now_add=True)  # Otomatis saat dibuat
updated_at = models.DateTimeField(auto_now=True)      # Otomatis saat diupdate
birth_date = models.DateField()                       # Tanggal saja

File Fields

# Field untuk file
image = models.ImageField(upload_to='products/')      # Untuk gambar
file = models.FileField(upload_to='documents/')       # Untuk file

3. Relasi Antar Model

One-to-Many (ForeignKey)

class Category(models.Model):
    name = models.CharField(max_length=100)
 
class Product(models.Model):
    category = models.ForeignKey(
        Category,
        on_delete=models.CASCADE,
        related_name='products'
    )

Many-to-Many

class Tag(models.Model):
    name = models.CharField(max_length=50)
 
class Product(models.Model):
    tags = models.ManyToManyField(Tag, related_name='products')

One-to-One

class UserProfile(models.Model):
    user = models.OneToOneField(
        'auth.User',
        on_delete=models.CASCADE
    )

4. Model Methods dan Properties

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
 
    # Method Instance
    def get_discount_price(self):
        return self.price * 0.9
 
    # Property
    @property
    def tax_amount(self):
        return self.price * 0.1
 
    # Method Static
    @staticmethod
    def get_total_products():
        return Product.objects.count()

5. Model Manager dan Queryset

# Custom Manager
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(status='published')
 
class Article(models.Model):
    # ... fields ...
    objects = models.Manager()           # Default manager
    published = PublishedManager()       # Custom manager

6. Meta Options

class Product(models.Model):
    # ... fields ...
 
    class Meta:
        ordering = ['-created_at']       # Pengurutan default
        verbose_name = 'Product'         # Nama tunggal
        verbose_name_plural = 'Products' # Nama jamak
        unique_together = ['name', 'category']  # Kombinasi unik

7. Validasi Model

from django.core.exceptions import ValidationError
 
class Product(models.Model):
    price = models.DecimalField(max_digits=10, decimal_places=2)
 
    def clean(self):
        if self.price < 0:
            raise ValidationError('Harga tidak boleh negatif')
 
    def save(self, *args, **kwargs):
        self.full_clean()
        super().save(*args, **kwargs)

8. Migrations

Perintah dasar untuk migrations:

# Membuat migrations
python manage.py makemigrations
 
# Menjalankan migrations
python manage.py migrate
 
# Melihat status migrations
python manage.py showmigrations
 
# Melihat SQL dari migrations
python manage.py sqlmigrate app_name migration_name

9. Contoh Penggunaan Model

# Membuat objek baru
product = Product.objects.create(
    name="Laptop",
    price=1000.00,
    category_id=1
)
 
# Query dasar
all_products = Product.objects.all()
laptop = Product.objects.get(name="Laptop")
cheap_products = Product.objects.filter(price__lt=500)
expensive_products = Product.objects.exclude(price__lt=500)