ruk·si

🍡 Django Tutorial
Mixins

Updated at 2018-11-23 18:12

You use model mixins to add shareable functionality to models.

  • UUIDMixin turns primary keys to UUIDs instead of integers.
  • TimesMixin instructs models to record when they were created and modified.

Create djangor/model_mixins/uuid_mixin.py:

import uuid
from django.db import models


class UUIDMixin(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        verbose_name='ID'
    )

    class Meta:
        abstract = True

Create djangor/model_mixins/times_mixin.py :

from django.db import models


class TimesMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Create djangor/model_mixins/__init__.py:

from .times_mixin import TimesMixin
from .uuid_mixin import UUIDMixin