# Imports
from django.db import models
from django.utils.translation import ugettext_lazy as _
# from superdjango.shortcuts import there_can_be_only_one
from .mixins import PrimaryMixin
# Exports
__all__ = (
"PrimaryModel",
)
# Constants
# Models
[docs]class PrimaryModel(PrimaryMixin):
"""Allows a record to be marked as "primary".
This model supplies the following:
- A ``NullBooleanField`` called ``is_primary``.
- Two static methods for use with the ``pre_save`` signal: ``allow_one_primary()`` and ``require_one_primary()``.
.. code-block:: py
# models.py
from django.db import models
from superdjango.db.primary.models import PrimaryModel
class Address(models.Model):
# A contact's address.
class Contact(models.Model):
# A contact in an address book.
class LinkContactAddress(PrimaryModel):
# Connect contacts with addresses.
address = models.ForeignKey(Address)
contact = models.ForeignKey(Contact)
# receivers.py
from django.db.models.signals import pre_save
from .models import LinkContactAddress
pre_save.connect(
LinkContactAddress.allow_one_primary,
LinkContactAddress,
dispath_uid="linkcontactaddress_allow_one_primary"
)
# Or to require a primary record.
pre_save.connect(
LinkContactAddress.require_one_primary,
LinkContactAddress,
dispath_uid="linkcontactaddress_require_one_primary"
)
"""
is_primary = models.NullBooleanField(
_("primary"),
help_text=_("Indicates that this is the primary record.")
)
class Meta:
abstract = True