Mapping strings to strings with HStoreField - a PostgreSQL specific field
Syntax#
- FooModel.objects.filter(field_name__key_name=‘value to query’)
Setting up HStoreField
First, we’ll need to do some setup to get HStoreField working.
-
make sure
django.contrib.postgresis in your `INSTALLED_APPS -
Add
HStoreExtensionto your migrations. Remember to putHStoreExtensionbefore anyCreateModelorAddFieldmigrations.from django.contrib.postgres.operations import HStoreExtension from django.db import migrations
class FooMigration(migrations.Migration): # put your other migration stuff here operations = [ HStoreExtension(), … ]
Adding HStoreField to your model
->Note: make sure you set upHStoreFieldfirst before going on with this example. (above)
No parameters are required for initializing a HStoreField.
from django.contrib.postgres.fields import HStoreField
from django.db import models
class Catalog(models.model):
name = models.CharField(max_length=200)
titles_to_authors = HStoreField()Creating a new model instance
Pass a native python dictionary mapping strings to strings to create().
Catalog.objects.create(name='Library of Congress', titles_to_authors={
'Using HStoreField with Django': 'CrazyPython and la communidad',
'Flabbergeists and thingamajigs': 'La Artista Fooista',
'Pro Git': 'Scott Chacon and Ben Straub',
})