django-es / django-elasticsearch-dsl

This is a package that allows indexing of django models in elasticsearch with elasticsearch-dsl-py.
Other
1.01k stars 263 forks source link

Compatibility with django-countries #484

Open debnet opened 1 month ago

debnet commented 1 month ago

Hello,

I want to include language in my index document but in my project these fields are CountryField from django-countries third-party app (https://github.com/SmileyChris/django-countries) and can't be serialized when rebuilding the index.

I tried to create a custom field with (de-)serialize override to text but in the to_dict() result the behaviour doesn't seem to work. I may have missed something in the documentation, I would appreciate some insight on this.

All the best.

debnet commented 1 month ago

I tried something like this but it doesn't work, and the documentation is not helpful.

class CustomCountryField(fields.TextField):
    def serialize(self, data):
        return data.code

@registry.register_document
class ArticleDocument(Document):
    country = CustomCountryField()
    ...

    @classmethod
    def get_model_field_class_to_field_class(cls):
        field_mapping = super().get_model_field_class_to_field_class()
        field_mapping[CountryField] = CustomCountryField
        return field_mapping
safwanrahman commented 1 month ago

I need to look at it. Will get back to you shortly

debnet commented 1 month ago

I managed to workaround by overriding get_value_from_instance method.

class CustomCountryField(fields.TextField):
    def get_value_from_instance(self, instance, field_value_to_ignore=None):
        value = super().get_value_from_instance(instance, field_value_to_ignore)
        return value.code if value else ""