├── .bumpversion.cfg ├── .dependabot └── config.yml ├── .gitignore ├── .isort.cfg ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── README.rst ├── django_ulid ├── __init__.py ├── forms.py ├── models.py └── serializers.py ├── pytest.ini ├── requirements ├── base.txt ├── build.txt ├── dev.txt ├── docs.txt ├── test.txt ├── tox.txt └── travis.txt ├── setup.cfg ├── setup.py ├── tests ├── settings.py ├── test_forms.py ├── test_models.py └── test_serializers.py └── tox.ini /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.0.4 3 | tag = True 4 | commit = True 5 | 6 | [bumpversion:file:django_ulid/__init__.py] 7 | 8 | -------------------------------------------------------------------------------- /.dependabot/config.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | update_configs: 3 | - package_manager: "python" 4 | directory: "/" 5 | update_schedule: "weekly" 6 | default_labels: 7 | - "type: maintenance" 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # PyCharm 104 | .idea/ 105 | -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | line_length = 120 3 | not_skip = __init__.py 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | cache: pip 4 | matrix: 5 | allow_failures: 6 | - env: TOXENV=py36-djmaster 7 | - env: TOXENV=py37-djmaster 8 | - env: TOXENV=py38-djmaster 9 | include: 10 | - python: '3.6' 11 | env: TOXENV=lint 12 | - python: '3.6' 13 | env: TOXENV=scan 14 | - python: '3.5' 15 | env: TOXENV=py35-dj21 16 | - python: '3.6' 17 | env: TOXENV=py36-dj21 18 | - python: '3.7' 19 | env: TOXENV=py37-dj21 20 | - python: '3.8' 21 | env: TOXENV=py38-dj21 22 | - python: '3.5' 23 | env: TOXENV=py35-dj22 24 | - python: '3.6' 25 | env: TOXENV=py36-dj22 26 | - python: '3.7' 27 | env: TOXENV=py37-dj22 28 | - python: '3.8' 29 | env: TOXENV=py38-dj21 30 | - python: '3.6' 31 | env: TOXENV=py36-dj30 32 | - python: '3.7' 33 | env: TOXENV=py37-dj30 34 | - python: '3.8' 35 | env: TOXENV=py38-dj30 36 | - python: '3.6' 37 | env: TOXENV=py36-dj31 38 | - python: '3.7' 39 | env: TOXENV=py37-dj31 40 | - python: '3.8' 41 | env: TOXENV=py38-dj31 42 | - python: '3.6' 43 | env: TOXENV=py36-djmaster 44 | - python: '3.7' 45 | env: TOXENV=py37-djmaster 46 | - python: '3.8' 47 | env: TOXENV=py38-djmaster 48 | install: make travis-install 49 | before_script: make travis-before-script 50 | script: make travis-script 51 | after_success: make travis-after-success 52 | deploy: 53 | - provider: pypi 54 | server: https://upload.pypi.org/legacy/ 55 | user: Andrew.Hawker 56 | password: 57 | secure: DiAGaB9U0B9LeQodJMBwkozE5QlTUqzAIxpANl1n6NyxpAnwVmWKjpReEGLmmjCFy4e0XJnGEd/IfL8fum0HjcQN3gnzKOinNRNrP31LCpK7nsP/5YjsHc23h5RtyjX35al+NUrkegXh2hpyWiSwzrfyp8BtEc1N3O99XcIk+bJGYhqpxOSgWW7pGb86vQSi4z1OU1n5Wzp0hG0e5eia0bmROwW2jEapgmkG5cHvKU+Y45b3oFklQXv3gjYN2Ti1zSkGMgG3Jyjkb6fpkgWVTIU+WYX37ROZbH85hW5DcYxuj/gR/Ys60uzpTCeGXMsDx5ylQ+6Lfntlis+iNaG22NeoasP6K0oQC+/jnQhCx+NVMnxko3kaelDFVX2SNdhXA+VpnwMYZQ+yt9WJgDJa/3hh0+ztgPwOLmxqIp2QL1vTOBTjMkqqOZ3HPx+NSXe1XSQv6YGjUclNXXyntXyLB01YsPgoXbTUnyXJbSjDN/ov7LmSfrzMP5JvJ2x8MgiOrZMrLYFM/xsF+AutLhUtFWH+MW3U0R5L2VRVqF2FTqlA1tbjrqtSYFQOhJMaIqNfjxlzJhd+qO2G/lG9d0UygHexGjwLODVNqi5m4bwjUS/33WH3CcAYkmqFzYccKJD0/F0lQTOExipqe6tfik9wzGVWDYBs+mDGZA+sxzOHNE4= 58 | distributions: sdist bdist_wheel 59 | skip_cleanup: true 60 | on: 61 | branch: master 62 | tags: true 63 | condition: $TOXENV = "py37-dj30" 64 | env: 65 | global: 66 | - VIRTUALENV_NO_DOWNLOAD=1 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Andrew R. Hawker 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .DEFAULT_GOAL := help 2 | 3 | .PHONY: changelog 4 | changelog: ## Build CHANGELOG.md from git/github metadata. Assumes 'CHANGELOG_GITHUB_TOKEN in env. 5 | @github_changelog_generator -u ahawker -p django-ulid 6 | 7 | .PHONY: test-install 8 | test-install: ## Install dependencies required for local test execution. 9 | @pip install -q -r requirements/test.txt 10 | 11 | .PHONY: test 12 | test: test-install ## Run test suite. 13 | @py.test -v tests 14 | 15 | .PHONY: scan 16 | scan: test-install ## Run security scan. 17 | @safety check 18 | 19 | .PHONY: tox-install 20 | tox-install: ## Install dependencies required for local test execution using tox. 21 | @pip install -q -r requirements/tox.txt 22 | 23 | .PHONY: tox 24 | tox: tox-install ## Run test suite using tox. 25 | @tox 26 | 27 | .PHONY: travis-install 28 | travis-install: ## Install dependencies for travis-ci.org integration. 29 | @pip install -q -r requirements/travis.txt 30 | 31 | .PHONY: travis-before-script 32 | travis-before-script: travis-install ## Entry point for travis-ci.org 'before_script' execution. 33 | @curl -s https://codecov.io/bash > ./codecov 34 | @chmod +x ./codecov 35 | 36 | .PHONY: travis-script 37 | travis-script: travis-install tox ## Entry point for travis-ci.org execution. 38 | 39 | .PHONY: travis-after-success 40 | travis-after-success: ## Entry point for travis-ci.org 'after_success' execution. 41 | @./codecov -e TOX_ENV 42 | 43 | .PHONY: codeclimate 44 | codeclimate: ## Run codeclimate analysis. 45 | @docker run \ 46 | --interactive --tty --rm \ 47 | --env CODECLIMATE_CODE="$(shell pwd)" \ 48 | --volume "$(shell pwd)":/code \ 49 | --volume /var/run/docker.sock:/var/run/docker.sock \ 50 | --volume /tmp/cc:/tmp/cc \ 51 | codeclimate/codeclimate analyze 52 | 53 | .PHONY: isort 54 | isort: ## Run isort on the package. 55 | @isort --recursive --check-only django_ulid tests 56 | 57 | .PHONY: mypy 58 | mypy: ## Run mypy static analysis checks on the package. 59 | @mypy django_ulid 60 | 61 | .PHONY: seclint 62 | seclint: ## Run bandit on the package. 63 | @bandit -v -r django_ulid 64 | 65 | .PHONY: lint 66 | lint: seclint isort ## Run mypy, seclint, and isort on the package. 67 | 68 | .PHONY: bump-patch 69 | bump-patch: ## Bump package patch version, e.g. 0.0.1 -> 0.0.2. 70 | @bumpversion patch 71 | 72 | .PHONY: bump-minor 73 | bump-minor: ## Bump package minor version, e.g. 0.1.0 -> 0.2.0. 74 | @bumpversion minor 75 | 76 | .PHONY: bump-major 77 | bump-major: ## Bump package major version, e.g. 1.0.0 -> 2.0.0. 78 | @bumpversion major 79 | 80 | .PHONY: git-push-with-tags 81 | git-push-with-tags: ## Push latest changes to remote with tags. 82 | @git push 83 | @git push --tags 84 | 85 | .PHONY: push-patch 86 | push-patch: bump-patch git-push-with-tags ## Bump package patch version and push changes to remote. 87 | 88 | .PHONY: push-minor 89 | push-minor: bump-minor git-push-with-tags ## Bump package minor version and push changes to remote. 90 | 91 | .PHONY: push-major 92 | push-major: bump-major git-push-with-tags ## Bump package major version and push changes to remote. 93 | 94 | .PHONY: clean-pyc 95 | clean-pyc: ## Remove local python cache files. 96 | @find . -name '__pycache__' -type d -exec rm -r {} + 97 | @find . -name '*.pyc' -exec rm -f {} + 98 | @find . -name '*.pyo' -exec rm -f {} + 99 | @find . -name '*~' -exec rm -f {} + 100 | 101 | .PHONY: readme 102 | readme: ## Convert README.md to README.rst used for setup.py 103 | @pandoc --from=markdown --to=rst --output=README.rst README.md 104 | 105 | .phony: help 106 | help: ## Print Makefile usage. 107 | @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST) 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-ulid 2 | 3 | [![Build Status](https://travis-ci.org/ahawker/django-ulid.svg?branch=master)](https://travis-ci.org/ahawker/django-ulid) 4 | [![codecov](https://codecov.io/gh/ahawker/django-ulid/branch/master/graph/badge.svg)](https://codecov.io/gh/ahawker/django-ulid) 5 | [![Code Climate](https://codeclimate.com/github/ahawker/django-ulid/badges/gpa.svg)](https://codeclimate.com/github/ahawker/django-ulid) 6 | [![Issue Count](https://codeclimate.com/github/ahawker/django-ulid/badges/issue_count.svg)](https://codeclimate.com/github/ahawker/django-ulid) 7 | 8 | [![PyPI Version](https://badge.fury.io/py/django-ulid.svg)](https://badge.fury.io/py/django-ulid) 9 | [![PyPI Versions](https://img.shields.io/pypi/pyversions/django-ulid.svg)](https://pypi.python.org/pypi/django-ulid) 10 | 11 | [Universally Unique Lexicographically Sortable Identifier (ULID)](https://github.com/alizain/ulid) support in [Django](https://www.djangoproject.com/). 12 | 13 | ### Status 14 | 15 | This project is actively maintained. 16 | 17 | ### Installation 18 | 19 | To install django-ulid from [pip](https://pypi.python.org/pypi/pip): 20 | ```bash 21 | $ pip install django-ulid 22 | ``` 23 | 24 | To install ulid from source: 25 | ```bash 26 | $ git clone git@github.com:ahawker/django-ulid.git 27 | $ cd django-ulid && python setup.py install 28 | ``` 29 | 30 | ### Usage 31 | 32 | Adding a ULID field to your Django models is straightforward. It can be a normal field or a primary key. 33 | 34 | ```python 35 | from django.db import models 36 | from django_ulid.models import default, ULIDField 37 | 38 | class Person(models.Model): 39 | id = ULIDField(default=default, primary_key=True, editable=False) 40 | ``` 41 | 42 | Passing in `default` to the `ULIDField` will automatically create a default value using the [ulid.new](https://ulid.readthedocs.io/en/latest/api.html#ulid.api.new) function. 43 | If you do not want a default value, `None` by default, feel free to omit it. 44 | 45 | ```python 46 | from django.db import models 47 | from django_ulid.models import ULIDField 48 | 49 | class Person(models.Model): 50 | optional_id = ULIDField() 51 | ``` 52 | 53 | Adding a ULID field to your [Django REST Framework](https://www.django-rest-framework.org/) serializers is also straightforward. 54 | 55 | Simply importing the `django_ulid.serializers` module will automatically register the `ULIDField` serializer by overriding 56 | the [serializer_field_mapping](https://www.django-rest-framework.org/api-guide/serializers/#customizing-field-mappings) on the default [ModelSerializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer). 57 | 58 | ```python 59 | from django_ulid import serializers 60 | ``` 61 | 62 | If you are using a ULID as a primary key on a model, you need to create a custom [PrimaryKeyRelatedField](https://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield) to automatically serialize 63 | the instance through the foreign key. 64 | 65 | ```python 66 | import functools 67 | from django_ulid.serializers import ULIDField 68 | from rest_framework import serializers 69 | 70 | PersonPrimaryKeyRelatedField = functools.partial(serializers.PrimaryKeyRelatedField, 71 | allow_null=True, 72 | allow_empty=True, 73 | pk_field=ULIDField(), 74 | queryset=Person.objects.all()) 75 | 76 | class OrganizationSerializer(serializers.ModelSerializer): 77 | owner = PersonPrimaryKeyRelatedField() 78 | ``` 79 | 80 | ### Contributing 81 | 82 | If you would like to contribute, simply fork the repository, push your changes and send a pull request. 83 | Pull requests will be brought into the `master` branch via a rebase and fast-forward merge with the goal of having a linear branch history with no merge commits. 84 | 85 | ### License 86 | 87 | [Apache 2.0](LICENSE) 88 | 89 | ### Dependencies 90 | 91 | * [Django](https://github.com/django/django) 92 | * [ulid-py](https://github.com/ahawker/ulid) 93 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | django-ulid 2 | =========== 3 | 4 | |Build Status| |codecov| |Code Climate| |Issue Count| 5 | 6 | |PyPI Version| |PyPI Versions| 7 | 8 | `Universally Unique Lexicographically Sortable Identifier 9 | (ULID) `__ support in 10 | `Django `__. 11 | 12 | Status 13 | ~~~~~~ 14 | 15 | This project is actively maintained. 16 | 17 | Installation 18 | ~~~~~~~~~~~~ 19 | 20 | To install django-ulid from `pip `__: 21 | 22 | .. code:: bash 23 | 24 | $ pip install django-ulid 25 | 26 | To install ulid from source: 27 | 28 | .. code:: bash 29 | 30 | $ git clone git@github.com:ahawker/django-ulid.git 31 | $ cd django-ulid && python setup.py install 32 | 33 | Usage 34 | ~~~~~ 35 | 36 | Adding a ULID field to your Django models is straightforward. It can be 37 | a normal field or a primary key. 38 | 39 | .. code:: python 40 | 41 | from django.db import models 42 | from django_ulid.models import default, ULIDField 43 | 44 | class Person(models.Model): 45 | id = ULIDField(default=default, primary_key=True, editable=False) 46 | 47 | Passing in ``default`` to the ``ULIDField`` will automatically create a 48 | default value using the 49 | `ulid.new `__ 50 | function. If you do not want a default value, ``None`` by default, feel 51 | free to omit it. 52 | 53 | .. code:: python 54 | 55 | from django.db import models 56 | from django_ulid.models import ULIDField 57 | 58 | class Person(models.Model): 59 | optional_id = ULIDField() 60 | 61 | Adding a ULID field to your `Django REST 62 | Framework `__ serializers is 63 | also straightforward. 64 | 65 | Simply importing the ``django_ulid.serializers`` module will 66 | automatically register the ``ULIDField`` serializer by overriding the 67 | `serializer_field_mapping `__ 68 | on the default 69 | `ModelSerializer `__. 70 | 71 | .. code:: python 72 | 73 | from django_ulid import serializers 74 | 75 | If you are using a ULID as a primary key on a model, you need to create 76 | a custom 77 | `PrimaryKeyRelatedField `__ 78 | to automatically serialize the instance through the foreign key. 79 | 80 | .. code:: python 81 | 82 | import functools 83 | from django_ulid.serializers import ULIDField 84 | from rest_framework import serializers 85 | 86 | PersonPrimaryKeyRelatedField = functools.partial(serializers.PrimaryKeyRelatedField, 87 | allow_null=True, 88 | allow_empty=True, 89 | pk_field=ULIDField(), 90 | queryset=Person.objects.all()) 91 | 92 | class OrganizationSerializer(serializers.ModelSerializer): 93 | owner = PersonPrimaryKeyRelatedField() 94 | 95 | Contributing 96 | ~~~~~~~~~~~~ 97 | 98 | If you would like to contribute, simply fork the repository, push your 99 | changes and send a pull request. Pull requests will be brought into the 100 | ``master`` branch via a rebase and fast-forward merge with the goal of 101 | having a linear branch history with no merge commits. 102 | 103 | License 104 | ~~~~~~~ 105 | 106 | `Apache 2.0 `__ 107 | 108 | Dependencies 109 | ~~~~~~~~~~~~ 110 | 111 | - `Django `__ 112 | - `ulid-py `__ 113 | 114 | .. |Build Status| image:: https://travis-ci.org/ahawker/django-ulid.svg?branch=master 115 | :target: https://travis-ci.org/ahawker/django-ulid 116 | .. |codecov| image:: https://codecov.io/gh/ahawker/django-ulid/branch/master/graph/badge.svg 117 | :target: https://codecov.io/gh/ahawker/django-ulid 118 | .. |Code Climate| image:: https://codeclimate.com/github/ahawker/django-ulid/badges/gpa.svg 119 | :target: https://codeclimate.com/github/ahawker/django-ulid 120 | .. |Issue Count| image:: https://codeclimate.com/github/ahawker/django-ulid/badges/issue_count.svg 121 | :target: https://codeclimate.com/github/ahawker/django-ulid 122 | .. |PyPI Version| image:: https://badge.fury.io/py/django-ulid.svg 123 | :target: https://badge.fury.io/py/django-ulid 124 | .. |PyPI Versions| image:: https://img.shields.io/pypi/pyversions/django-ulid.svg 125 | :target: https://pypi.python.org/pypi/django-ulid 126 | -------------------------------------------------------------------------------- /django_ulid/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | django_ulid 3 | ~~~~~~~~~~~ 4 | 5 | Universally Unique Lexicographically Sortable Identifier (ULID) support in Django 6 | 7 | :copyright: (c) 2019 Andrew Hawker. 8 | :license: Apache 2.0, see LICENSE for more details. 9 | """ 10 | __version__ = '0.0.4' 11 | -------------------------------------------------------------------------------- /django_ulid/forms.py: -------------------------------------------------------------------------------- 1 | """ 2 | django_ulid/forms 3 | ~~~~~~~~~~~~~~~~~ 4 | 5 | Contains functionality for Django form support. 6 | """ 7 | import ulid 8 | from django import forms 9 | from django.core import exceptions 10 | from django.utils.translation import gettext as _ 11 | 12 | 13 | class ULIDField(forms.CharField): 14 | """ 15 | Django form field type for handling ULID values. 16 | """ 17 | def prepare_value(self, value): 18 | return str(ulid.parse(value)) if value is not None else "" 19 | 20 | def to_python(self, value): 21 | value = super().to_python(value) 22 | 23 | if value in self.empty_values: 24 | return None 25 | try: 26 | return ulid.parse(value) 27 | except (AttributeError, ValueError): 28 | raise exceptions.ValidationError(_('Enter a valid ULID.'), code='invalid') 29 | -------------------------------------------------------------------------------- /django_ulid/models.py: -------------------------------------------------------------------------------- 1 | """ 2 | django_ulid/models 3 | ~~~~~~~~~~~~~~~~~~ 4 | 5 | Contains functionality for Django model support. 6 | """ 7 | import ulid 8 | from django.core import exceptions 9 | from django.db import models 10 | from django.utils.translation import gettext as _ 11 | 12 | from . import forms 13 | 14 | # Helper attr so callers don't need to import the ulid package. 15 | default = ulid.new 16 | 17 | 18 | class ULIDField(models.Field): 19 | """ 20 | Django model field type for handling ULID's. 21 | 22 | This field type is natively stored in the DB as a UUID (when supported) and a string/varchar otherwise. 23 | """ 24 | description = 'Universally Unique Lexicographically Sortable Identifier' 25 | empty_strings_allowed = False 26 | 27 | def __init__(self, verbose_name=None, **kwargs): 28 | kwargs.setdefault('max_length', 26) 29 | super().__init__(verbose_name, **kwargs) 30 | 31 | def deconstruct(self): 32 | name, path, args, kwargs = super().deconstruct() 33 | del kwargs['max_length'] 34 | return name, path, args, kwargs 35 | 36 | def get_internal_type(self): 37 | return 'UUIDField' 38 | 39 | def get_db_prep_value(self, value, connection, prepared=False): 40 | if value is None: 41 | return None 42 | if not isinstance(value, ulid.ULID): 43 | value = self.to_python(value) 44 | return value.uuid if connection.features.has_native_uuid_field else str(value) 45 | 46 | def from_db_value(self, value, expression, connection): 47 | return self.to_python(value) 48 | 49 | def to_python(self, value): 50 | if value is None: 51 | return None 52 | try: 53 | return ulid.parse(value) 54 | except (AttributeError, ValueError): 55 | raise exceptions.ValidationError( 56 | _("'%(value)s' is not a valid ULID."), 57 | code='invalid', 58 | params={'value': value} 59 | ) 60 | 61 | def formfield(self, **kwargs): 62 | return super().formfield(**{ 63 | 'form_class': forms.ULIDField, 64 | **kwargs, 65 | }) 66 | -------------------------------------------------------------------------------- /django_ulid/serializers.py: -------------------------------------------------------------------------------- 1 | """ 2 | django_ulid/serializers 3 | ~~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | Contains functionality for Django REST Framework (DRF) serializer support. 6 | """ 7 | import ulid 8 | from django.utils.translation import gettext as _ 9 | from rest_framework import fields, serializers 10 | 11 | from . import models 12 | 13 | 14 | class ULIDField(fields.Field): 15 | """ 16 | Django REST Framework (DRF) serializer field type for handling ULID's. 17 | """ 18 | default_error_messages = { 19 | 'invalid': _('"{value}" is not a valid ULID.'), 20 | } 21 | 22 | def to_internal_value(self, data): 23 | try: 24 | return ulid.parse(data) 25 | except (AttributeError, ValueError): 26 | self.fail('invalid', value=data) 27 | 28 | def to_representation(self, value): 29 | return str(ulid.parse(value)) 30 | 31 | 32 | # Register the DRF serializer field with the Django ULID model field so the DRF model 33 | # serializer can automatically detect/use the field without requiring serializers to specify it. 34 | serializers.ModelSerializer.serializer_field_mapping[models.ULIDField] = ULIDField 35 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | DJANGO_SETTINGS_MODULE = tests.settings 3 | addopts = --cov-report xml --cov-config .coveragerc --cov=django_ulid 4 | 5 | -------------------------------------------------------------------------------- /requirements/base.txt: -------------------------------------------------------------------------------- 1 | # django-ulid/requirements/base.txt 2 | # 3 | # Requirements for using this package. 4 | 5 | -r build.txt 6 | 7 | typing==3.7.4.1; python_version < '3.6' 8 | 9 | ulid-py==1.1.0 10 | -------------------------------------------------------------------------------- /requirements/build.txt: -------------------------------------------------------------------------------- 1 | # django-uild/requirements/build.txt 2 | # 3 | # Requirements necessary to build this package. 4 | 5 | setuptools==51.1.0.post20201221 6 | -------------------------------------------------------------------------------- /requirements/dev.txt: -------------------------------------------------------------------------------- 1 | # django-ulid/requirements/dev.txt 2 | # 3 | # Requirements for using developing package. 4 | 5 | -r base.txt 6 | 7 | bumpversion==0.6.0 8 | mypy==0.670; python_version <= '3.4' # pyup: ignore 9 | mypy==0.790; python_version > '3.4' 10 | safety==1.10.0 11 | bandit==1.7.0 12 | isort==4.2.15; (python_version > '3.0' and python_version < '3.4') # pyup: ignore 13 | isort==4.3.21; (python_version > '2.7' and python_version < '3.0') or python_version >= '3.4' 14 | -------------------------------------------------------------------------------- /requirements/docs.txt: -------------------------------------------------------------------------------- 1 | # django-ulid/requirements/docs.txt 2 | # 3 | # Requirements for generating package documentation. 4 | 5 | -r base.txt 6 | 7 | sphinx==3.5.0 8 | sphinx_rtd_theme==0.5.0 9 | -------------------------------------------------------------------------------- /requirements/test.txt: -------------------------------------------------------------------------------- 1 | # django-ulid/requirements/test.txt 2 | # 3 | # Requirements for executing test suite. 4 | 5 | -r dev.txt 6 | 7 | djangorestframework==3.12.2 8 | 9 | coverage==5.3.1 10 | factory-boy==3.2.0 11 | 12 | pytest==6.2.1 13 | pytest-benchmark==3.2.3 14 | pytest-cov==2.10.1 15 | pytest-django==4.1.0 16 | pytest-factoryboy==2.0.3 17 | pytest-helpers-namespace==2019.1.8 18 | pytest-mock==3.5.1 19 | pytest-pep8==1.0.6 20 | -------------------------------------------------------------------------------- /requirements/tox.txt: -------------------------------------------------------------------------------- 1 | # django-ulid/requirements/tox.txt 2 | # 3 | # Requirements for executing test suite using tox. 4 | 5 | -r test.txt 6 | 7 | tox==3.20.1 8 | -------------------------------------------------------------------------------- /requirements/travis.txt: -------------------------------------------------------------------------------- 1 | # django-ulid/requirements/travis.txt 2 | # 3 | # Requirements for executing the test suite on Travis CI. 4 | 5 | -r tox.txt 6 | 7 | tox-travis==0.12 8 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [metadata] 5 | description-file = README.md 6 | license_file = LICENSE 7 | 8 | [pep8] 9 | max-line-length = 120 10 | 11 | [flake8] 12 | ignore = F403 13 | exclude = django_ulid/__init__.py 14 | max-line-length = 120 15 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | django_ulid 3 | ~~~~~~~~~~~ 4 | 5 | Universally Unique Lexicographically Sortable Identifier (ULID) support in Django. 6 | 7 | :copyright: (c) 2019 Andrew Hawker. 8 | :license: Apache 2.0, see LICENSE for more details. 9 | """ 10 | import ast 11 | import re 12 | 13 | 14 | try: 15 | from setuptools import setup 16 | except ImportError: 17 | from distutils.core import setup 18 | 19 | 20 | version_regex = re.compile(r'__version__\s+=\s+(.*)') 21 | 22 | 23 | def get_version(): 24 | with open('django_ulid/__init__.py', 'r') as f: 25 | return str(ast.literal_eval(version_regex.search(f.read()).group(1))) 26 | 27 | 28 | def get_long_description(): 29 | with open('README.rst') as f: 30 | return f.read() 31 | 32 | 33 | setup( 34 | name='django-ulid', 35 | version=get_version(), 36 | author='Andrew Hawker', 37 | author_email='andrew.r.hawker@gmail.com', 38 | url='https://github.com/ahawker/django-ulid', 39 | license='Apache 2.0', 40 | description='Universally Unique Lexicographically Sortable Identifier (ULID) support in Django', 41 | long_description=get_long_description(), 42 | packages=['django_ulid'], 43 | python_requires='>=3.5', 44 | install_requires=['Django>=2.1', 'ulid-py>=0.1.0'], 45 | classifiers=( 46 | 'Development Status :: 4 - Beta', 47 | "Framework :: Django", 48 | "Framework :: Django :: 1.11", 49 | "Framework :: Django :: 2.1", 50 | "Framework :: Django :: 2.2", 51 | "Framework :: Django :: 3.0", 52 | 'Intended Audience :: Developers', 53 | 'Natural Language :: English', 54 | 'License :: OSI Approved :: Apache Software License', 55 | 'Programming Language :: Python', 56 | 'Programming Language :: Python :: 3', 57 | 'Programming Language :: Python :: 3.5', 58 | 'Programming Language :: Python :: 3.6', 59 | 'Programming Language :: Python :: 3.7', 60 | 'Programming Language :: Python :: 3.8', 61 | 'Topic :: Software Development :: Libraries :: Python Modules' 62 | ) 63 | ) 64 | -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | settings 3 | ~~~~~~~~ 4 | 5 | Django settings for tests. 6 | """ 7 | 8 | DATABASES = { 9 | 'default': { 10 | 'ENGINE': 'django.db.backends.sqlite3' 11 | } 12 | } 13 | 14 | SECRET_KEY = 'secretkey' 15 | 16 | INSTALLED_APPS = [ 17 | 'django_ulid', 18 | 'tests' 19 | ] 20 | -------------------------------------------------------------------------------- /tests/test_forms.py: -------------------------------------------------------------------------------- 1 | """ 2 | test_forms 3 | ~~~~~~~~~~ 4 | 5 | Tests for the :mod:`~django_ulid.forms` module. 6 | """ 7 | import pytest 8 | 9 | from django_ulid import forms 10 | 11 | 12 | @pytest.mark.xfail(reason='TODO') 13 | def test_sanity(): 14 | assert False 15 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | """ 2 | test_models 3 | ~~~~~~~~~~~ 4 | 5 | Tests for the :mod:`~django_ulid.models` module. 6 | """ 7 | import pytest 8 | 9 | from django_ulid import models 10 | 11 | 12 | @pytest.mark.xfail(reason='TODO') 13 | def test_sanity(): 14 | assert False 15 | -------------------------------------------------------------------------------- /tests/test_serializers.py: -------------------------------------------------------------------------------- 1 | """ 2 | test_serializers 3 | ~~~~~~~~~~~~~~~~ 4 | 5 | Tests for the :mod:`~django_ulid.serializers` module. 6 | """ 7 | import pytest 8 | 9 | from django_ulid import serializers 10 | 11 | 12 | @pytest.mark.xfail(reason='TODO') 13 | def test_sanity(): 14 | assert False 15 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | lint 4 | scan 5 | py{35,36,37}-dj21 6 | py{35,36,37}-dj22 7 | py{36,37,38}-dj30 8 | py{36,37,38}-dj31 9 | py{36,37,38}-djmaster 10 | 11 | [testenv] 12 | deps = 13 | dj21: Django>=2.1,<2.2 14 | dj22: Django>=2.2,<3.0 15 | dj30: Django>=3.0a1,<3.1 16 | dj31: Django>=3.1a1,<3.2 17 | djmaster: https://github.com/django/django/archive/master.tar.gz 18 | commands = make test 19 | whitelist_externals = make 20 | usedevelop = true 21 | 22 | [testenv:lint] 23 | deps = 24 | django 25 | djangorestframework 26 | commands = make lint 27 | 28 | [testenv:scan] 29 | deps = 30 | django 31 | djangorestframework 32 | commands = make scan 33 | 34 | [travis] 35 | python = 36 | 3.5: py35 37 | 3.6: py36 38 | 3.7: py37 39 | 3.8: py38 40 | --------------------------------------------------------------------------------