Skip to main content

Django app to make one-to-one relations easier to work with

Project description

Smart One-To-One Field

For Django

pypi pre-commit.ci status

django-smartonetoonefield provides utility fields discussed in this Fusionbox blog post

Compatibility

  • Python: >= 3.12
  • Django: >= 4.2

Installation

  1. Install the latest version:

    pip install django-smartonetoonefield
    
    poetry add django-smartonetoonefield
    
  2. Add smartonetoonefield to INSTALLED_APPS in your project's settings.py.

Usage

AutoOneToOneField

If you can create a related model by just filling in one field, then AutoOneToOneField will simplify your code.

To use, define an AutoOneToOneField field on a model with a relation to another field. This will ensure that the related model object will always exist, even if it must be created upon first access.

models.py:

class CustomerProfile(models.Model):
    user = AutoOneToOneField('User', related_name='customer_profile')
user = User.objects.all()[0]
user.customer_profile  # Always returns a customer profile

SoftOneToOneField

If you cannot create the related model by simply setting the foreign key on the related model, then a SoftOneToOneField might work better for you.

With SoftOneToOneField, if the related model object exists, the lookup will work as normal. But if the related model object does not exist, then the attribute will be None.

models.py:

class CustomerProfile(models.Model):
    user = SoftOneToOneField('User', related_name='customer_profile')

views.py:

class MyProfileView(DetailView):
    def get_context_data(self, **kwargs):
        kwargs = super(MyProfileView, self).get_context_data(**kwargs)
        # This will not raise an exception if the customer_profile does
        # not exist
        kwargs.update(my_profile=self.customer_profile)
        return kwargs

AddFlagOneToOneField

Sometimes, when you need to check if a related model exists or not, it can be unwieldy to query the relation directly. A workaround to this is to define properties on the reverse related model:

models.py:

class User(AbstractUser):
    # ...
    def is_customer(self):
        return hasattr(self, 'customer_profile')


class CustomerProfile(models.Model):
    user = models.OneToOneField('User', related_name='customer_profile')

However, this can necessitate creating a custom default user model for a project, and this can be impossible if you need to override a model in a third party Django app.

Instead of overriding models or querying the related fields directly, the AddFlagOneToOneField will automatically add flags to the related model to make it easier to query related fields:

models.py:

class CustomerProfile(models.Model):
    user = AddFlagOneToOneField('auth.User', related_name='customer_profile',
                                flag_name='is_customer')


class MerchantProfile(models.Model):
    user = AddFlagOneToOneField('auth.User', related_name='merchant_profile',
                                flag_name='is_merchant')


class EmployeeProfile(models.Model):
    user = AddFlagOneToOneField('auth.User', related_name='employee_profile',
                                flag_name='is_employee')

views.py:

user = User.objects.get(email='customer@example.com')
user.is_customer  # True
user.is_merchant  # False
user.is_employee  # False

Since the AddFlagOneToOneField won't throw exceptions on access, you don't have to override, inherit, or modify other models when using the specified flags.

TODO

I have intentionally kept this app very small to minimize the maintenance burden. But contributions are very welcome!

License

BSD

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_smartonetoonefield-0.1.1.tar.gz (3.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_smartonetoonefield-0.1.1-py3-none-any.whl (4.0 kB view details)

Uploaded Python 3

File details

Details for the file django_smartonetoonefield-0.1.1.tar.gz.

File metadata

File hashes

Hashes for django_smartonetoonefield-0.1.1.tar.gz
Algorithm Hash digest
SHA256 6e7dac6b6d0083f3e3ee9afd8565e302d52403f4211b2a82e6614d4efc69f196
MD5 93cd695cd4115cf6f46b6366d9a98dba
BLAKE2b-256 b22e45d17fa606801d85606d56016c57708df8b6721730352d3459b606e41ec8

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_smartonetoonefield-0.1.1.tar.gz:

Publisher: publish.yaml on blag/django-smartonetoonefield

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file django_smartonetoonefield-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_smartonetoonefield-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 09a6703531a45e9e9e212dda84df29c125272251eeb5ebe92b1f0e9da5e78816
MD5 8a31b55a5147e22c1680cc69f9043fd5
BLAKE2b-256 7e64e281f059ce7bf3814cde552c0029a59393956bb7fe1dab74ec494286fdef

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_smartonetoonefield-0.1.1-py3-none-any.whl:

Publisher: publish.yaml on blag/django-smartonetoonefield

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page