applegrew / django-select2

This is a Django integration for Select2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

have chained dropdown with elasticsearch

yangmeijian opened this issue · comments

commented

I would like to have chained dropdown with elasticsearch as data backend. I still have no idea on connecting django-select2 with elasticsearch after many reading.

During the time, I re-studied the model_chained_select2_widget in testapp but still have no clue on connecting the form with the backend as I get django.db.utils.OperationError: no such table: testapp_country despite running python manage.py makemigrations and python manage.py migrate.

This is what I have:
https://stackoverflow.com/questions/58075671/django-select2-chained-dropdown-with-elasticsearch

Would it be possible to shed some light onto this? Thanks.

Hi @yangmeijian,

Thanks for reaching out. I hope a can be of help, but to be honest, you are maybe reaching the limits of what this library can provide. For this to work, you will need to write a little JavaScript code of your own.

Depending on your setup, you might able to interface with ElasticSearch directly. If you want are running your results through your application server, build a Django view, that does just that. Make sure you JSON API works and you can provide parameters to limit the result set.

Once you are certain that your API works as expected it's time to write some small JavaScript.

You will need to overwrite the ajax.data property to pass custom parameters to your search API, as described here: https://select2.org/data-sources/ajax#request-parameters

You can see, that we are doing the same thing in our implementation here:

data: function (params) {
var result = {
term: params.term,
page: params.page,
field_id: $element.data('field_id')
}
var dependentFields = $element.data('select2-dependent-fields')
if (dependentFields) {
dependentFields = dependentFields.trim().split(/\s+/)
$.each(dependentFields, function (i, dependentField) {
result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
})
}
return result

Of course, you could use the dependend-fields api, to pass custom parameters. But I believe you will have a clearn solution if you build everything yourself and don't use django-select2 but only select2 and your own backend code.

Please let me know if you need further assistance.

Best
-Joe