App allows you to easily tag a django db object with key/value pairs.
- Install package into Django runtime environment
- Add
django.contrib.humanize
andkvstore
to the list ofINSTALLED_APPS
insettings.py
of your Django project python manage.py migrate
Setup a model with a kvstore by simply including the register
method which appends a kvstore
attribute to the model.
# models.py
import kvstore
class Charity(models.Model):
...
kvstore.register(Charity)
charity = Charity.objects.get(pk=123)
charity.kvstore.set('foo', 'bar')
# Or set multiple key/values with a dictionary
charity.kvstore.set({'foo': 'bar'})
# Getting a single value
value = charity.kvstore.get('foo') # prints 'bar'
# Getting all key/values
tags = charity.kvstore.all() # returns dict of all tags
# You can also easily check if a key exists
exists = charity.kvstore.has('foo')
# Delete single tag
charity.kvstore.delete('foo')
# Delete multiple tags
charity.kvstore.delete(['foo', 'foo2'])
# Delete all
charity.kvstore.delete_all()
To add a kvstore to ModelAdmin
, just requires one line:
# model_admins.py
from kvstore.model_admin import TagInline
class CharityModelAdmin(ModelAdmin):
inlines = [TagInline]
...
# admin.py
from kvstore.admin.admin import KVStoreAdminApp
from kvstore.models import Tag
admin.site.register(Tag, KVStoreAdminApp)
Custom view is available at /admin/kvstore/tag/kvstore/upload
Note you can directly query the tag model as well. For example, if you want to get all objects that contain a key:
# All charity tags with a 'pilot' tag
ctype = ContentType.objects.get_for_model(Charity)
tags = Tag.objects.filter(content_type=ctype, key='pilot').all()
Built-in support for JSON as a value
- testing a Django package is like testing middleware, we have to set up a project instance we can import this package into
setup.py
contains Django project settingsINSTALLED_APPS
has an entry forkvstore.tests
tests
folder contains Django project files required for testing:admin.py
models.py
urls.py
- Create and activate virtual environment
pip install -r requirements.txt
python setup.py test