First, we'll need to do some setup to get HStoreField
working.
django.contrib.postgres
is in your `INSTALLED_APPSHStoreExtension
to your migrations. Remember to put HStoreExtension
before any CreateModel
or AddField
migrations.from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
class FooMigration(migrations.Migration):
# put your other migration stuff here
operations = [
HStoreExtension(),
...
]
->
Note: make sure you set upHStoreField
first 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()
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',
})
Catalog.objects.filter(titles__Pro_Git='Scott Chacon and Ben Straub')
Pass a dict
object to field_name__contains
as a keyword argument.
Catalog.objects.filter(titles__contains={
'Pro Git': 'Scott Chacon and Ben Straub'})
Equivalent to the SQL operator `@>`.