Create Document field inside Django elastic search for calculate properties

96 Views Asked by At

I have three models inside my Django model

class A(BaseModel):

    b = models.ForeignKey(B, null=True, blank=True, on_delete=models.SET_NULL)
    c = models.ForeignKey(C, null=True, blank=True, on_delete=models.SET_NULL)

    @property
    def tags(self):
        tags = []
        if self.c:
            tags.extend(self.c.tags.all())
        if self.document:
            tags.extend(self.b.tags.all())
        return tags


class B(BaseModel):

    tags = GenericRelation('tags.Tag')

class Tag(BaseModel):
    definition = models.ForeignKey(TagDefinition, on_delete=models.CASCADE)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField(db_index=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    task_id = models.CharField(max_length=150, null=True, blank=False)
    task_exception = models.TextField(null=True, blank=True)

    objects = TagManager()

In Elastic search I would like to create Document based on model A

All other fields are working well, but calculated field tags are not.

@registry.register_document
class AkDocument(Document):

    tags = fields.ListField(fields.ObjectField(properties={
            'definition': fields.ObjectField(properties={
                'friendly_name': fields.KeywordField(),
                'code': fields.KeywordField(),
                'variant': fields.KeywordField(),
            }),
            'task_id': fields.KeywordField(),
            'task_exception': fields.KeywordField(),
        }))

This will only return a {} even though tags are inside.

So if I check:

>>> ADocument().get_queryset()[0].tags
[<Tag: Tag object (1502)>]

>>> ADocument().search().execute()[0].tags
{}

How to construct this field so that it will return correct results?

0

There are 0 best solutions below