django-elasticsearch-dsl icon indicating copy to clipboard operation
django-elasticsearch-dsl copied to clipboard

Support for JSONField

Open MightySCollins opened this issue 7 years ago • 6 comments

Hi

I am trying to use the Django models JSONField but because its structure can be changed I am not sure of its properties. Is there anyway I can avoid setting them when using a ObjectField? Or can you think of any other solutions?

Without setting properties like below the following happens

attributes = fields.ObjectField()
"attributes": [
  {
  },
  {
  }
],

You package has saved me so much time, thanks.

MightySCollins avatar Jul 04 '17 09:07 MightySCollins

Hello,

I recently ran into the same issue. A (dirty ?) workaround is to use the prepare_foo function, something like this (in this example, "yourfield" is a relationship object with regular fields and a 'data' jsonfield):

class MyIndex(DocType):
    [...]

    yourfield = fields.ObjectField()

    def prepare_yourfield(self, instance):
        json_keys = [list_of_all_possible_keys_of_the_jsonfield]
        final_list = []

        for yourfield in instance.yourfields.all():
            # regular fields values
            fields_dict = {
                'attr1': yourfield.attr1,
                'attr2: yourfield.attr2,
                [...]
            }
            # flatten the json field values
            for k in keys:
                fields_dict[k] = yourfield.data.get(k)

            final_list.append(fields_dict)
    return final_list

Hope this helps :)

boccheciampe avatar Nov 21 '17 10:11 boccheciampe

i try this:

class MyType(DocType):
    content_json = fields.ObjectField()

    def prepare_content_json(self, instance):
        return instance.content_json

cocoakekeyu avatar Apr 08 '18 08:04 cocoakekeyu

so, part of it is in master:

https://github.com/sabricot/django-elasticsearch-dsl/pull/220

andreasnuesslein avatar Nov 28 '19 16:11 andreasnuesslein

i try this:

class MyType(DocType):
    content_json = fields.ObjectField()

    def prepare_content_json(self, instance):
        return instance.content_json

it works this solution?

Allan-Nava avatar Feb 12 '20 14:02 Allan-Nava

it works this solution?

? yes? did you try it? people are giving a thumbs up

andreasnuesslein avatar Feb 12 '20 19:02 andreasnuesslein