Performance: Primary key behavior
This affects database query speed and page load time by influencing how records are uniquely identified and indexed.
class Product(models.Model): sku = models.CharField(max_length=50, primary_key=True) name = models.CharField(max_length=100)
class Product(models.Model): name = models.CharField(max_length=100) sku = models.CharField(max_length=50, unique=True) # No explicit primary key, default id is used
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Default AutoField primary key | N/A | N/A | N/A | [!] OK |
| Natural key as primary key (e.g., SKU) | N/A | N/A | N/A | [OK] Good |
| Separate UUID unique field with AutoField PK | N/A | N/A | N/A | [X] Bad |
| UUIDField as primary key | N/A | N/A | N/A | [OK] Good |
id field as a primary key if none is specified.id field as the primary key. -> Option Bprimary_key=True.name = models.CharField(max_length=100, primary_key=True) uses primary_key=True correctly.class Product(models.Model):
sku = models.CharField(max_length=20, primary_key=True)
name = models.CharField(max_length=100)
p = Product(sku='X123', name='Widget')
p.save()
print(Product.objects.get(pk='X123').name)
What will be printed?sku field is set as primary key, so pk='X123' looks up by sku..name outputs 'Widget'.class Customer(models.Model):
id = models.IntegerField(primary_key=True)
id = models.CharField(max_length=10, primary_key=True)email field uniquely identifies each user and acts as the primary key. Which is the best way to define this model?class User(models.Model):
email = models.EmailField(primary_key=True)
name = models.CharField(max_length=100) sets email as primary key directly, which is correct. class User(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=100) only makes it unique but not primary key. class User(models.Model):
id = models.AutoField(primary_key=True)
email = models.EmailField(unique=True)
name = models.CharField(max_length=100) keeps default id as primary key. class User(models.Model):
email = models.EmailField()
name = models.CharField(max_length=100)
class Meta:
primary_key = 'email' uses invalid Meta syntax.Pass the test and this pattern moves unknown