简体   繁体   中英

How to use Django HStore DictionaryField in schema and schemaless mode at the same time?

When I use hstore.DictionaryField() in Django model passing no parameters and register my model in Djano admin I can create new key-value rows in admin interface on a fly.

When I use the same field in schema mode hstore.DictionaryField(schema=['some schema description']) I get fixed amount of fields described in schema parameter.

Can I have both of these features at the same time, namely, have several fixed fields of certain type listed in schema description while being able to add new fields as well?

Upd

One way of solving this could be using two DictionaryField's one with schema and other being schemaless but it is hardly an optimal solution.

The answer is no, you cannot have both with the current implementation of the hstore library. Take a look at the init function (this is from their source on github):

class DictionaryField(HStoreField):
    description = _("A python dictionary in a postgresql hstore field.")

    def __init__(self, *args, **kwargs):
        self.schema = kwargs.pop('schema', None)
        self.schema_mode = False
        # if schema parameter is supplied the behaviour is slightly different
        if self.schema is not None:
            self._validate_schema(self.schema)
            self.schema_mode = True
            # DictionaryField with schema is not editable via admin
            kwargs['editable'] = False
            # null defaults to True to facilitate migrations
            kwargs['null'] = kwargs.get('null', True)

        super(DictionaryField, self).__init__(*args, **kwargs)

You can see that if the schema is set, then the editable argument for the field is set to false, which is what the Django admin looks at to see if you should be allowed to edit the value in the admin UI.

Unfortunately, you only have a few options: override it yourself by creating your own class that inherits from that one, or open up a pull request or issue on their github page and hope that someone will get to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM