Skip to content

Django app that allows you to easily tag a django db object with key/value pairs.

Notifications You must be signed in to change notification settings

infoscout/kvstore

Repository files navigation

Key-Value Store

CircleCI codecov

App allows you to easily tag a django db object with key/value pairs.

Implementation

Installation

  1. Install package into Django runtime environment
  2. Add django.contrib.humanize and kvstore to the list of INSTALLED_APPS in settings.py of your Django project
  3. python manage.py migrate

Setting up a django model with a kvstore

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)

Storing key/value tags

charity = Charity.objects.get(pk=123)
charity.kvstore.set('foo', 'bar')

# Or set multiple key/values with a dictionary
charity.kvstore.set({'foo': 'bar'})

Returning key/value tags

# 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')

Deleting key/value tags

# Delete single tag
charity.kvstore.delete('foo')

# Delete multiple tags
charity.kvstore.delete(['foo', 'foo2'])

# Delete all
charity.kvstore.delete_all()

Adding kvstore to ModelAdmin

To add a kvstore to ModelAdmin, just requires one line:

# model_admins.py
from kvstore.model_admin import TagInline

class CharityModelAdmin(ModelAdmin):
  inlines = [TagInline]
  ...

Adding Custom Tags View to Django Admin

# 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

Other queries

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()

Future enhancements

Built-in support for JSON as a value

Contributing

Note on Testing Django Packages

  • 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 settings
    • INSTALLED_APPS has an entry for kvstore.tests
  • tests folder contains Django project files required for testing:
    • admin.py
    • models.py
    • urls.py

Setting up Development Environment

  1. Create and activate virtual environment
  2. pip install -r requirements.txt

Running tests

python setup.py test

About

Django app that allows you to easily tag a django db object with key/value pairs.

Resources

Stars

Watchers

Forks

Packages

No packages published