from django.db import models
class Product(models.Model):
name = models.CharField(max_length=200)
sku = models.CharField(max_length=50)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'shop_products'
ordering = ['-created_at', 'name']
verbose_name = 'Product'
verbose_name_plural = 'Products'
indexes = [
models.Index(fields=['category', '-created_at']),
models.Index(fields=['sku']),
]
unique_together = [
['sku', 'category']
]
permissions = [
('can_publish_product', 'Can publish product'),
('can_feature_product', 'Can feature product on homepage'),
]
def __str__(self):
return self.name
Model Meta class controls database behavior. I use ordering for default query ordering, indexes for database indexes, and unique_together for composite uniqueness constraints. The db_table option customizes table names. For large tables, managed=False creates unmanaged models for existing tables. I use verbose_name and verbose_name_plural for admin readability. Permissions can be added via permissions. These options optimize queries and define database structure without migrations for each change.