Skip to content

Commit

Permalink
Add BaseModelWithIdAndTimestamps Django model
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuatz committed Nov 12, 2024
1 parent 8e94074 commit cfb322d
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions django_utils_lib/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import uuid

from django.db import models


class BaseModelWithIdAndTimestamps(models.Model):
"""
This is a useful "base model" to have all your other models inherit from
It provides:
- A UUID(4) backed "id" property, as the primary key
- Timestamps (`created_date`, `modified_date`)
- Enforcement of validation rules on save (which is not Django's default behavior)
"""

id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) # noqa: A003

# Timestamps
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)

# Run all validation checks on model save (which is not the default behavior of Django)
def save(self, *args, **kwargs) -> None:
self.full_clean()
return super().save(*args, **kwargs)

class Meta:
abstract = True

0 comments on commit cfb322d

Please sign in to comment.