Dmitri-Sintsov / django-jinja-knockout

Django datatables and widgets, both AJAX and traditional. Display-only ModelForms. ModelForms / inline formsets with AJAX submit and validation. Works with Django templates.
https://django-jinja-knockout.readthedocs.org/
Other
144 stars 29 forks source link

KoGridView grid_fields use m2m field throws Invalid JSON data #18

Closed elros244 closed 2 years ago

elros244 commented 3 years ago

Hi, first of all, thanks for this work, it really helps to simplify stuff.

Now my question, it's possible to use and m2m field as a grid_fields in KoGridView? I ask this because I have an KoGridView and in grid_fields I want to display Django user groups like this:

grid_fields = [
        ("username", "Username"),
        ("first_name", "Name"),
        ("last_name", "Last Name"),
        ("groups", "Groups"),
    ]

But when it's time to render the KoGridView throws this error:

Invalid JSON data, key path: 0 / entries / 1 / groups, val type: django.db.models.fields.related_descriptors.create_forward_many_to_many_manager..ManyRelatedManager

I need to specify this differently in grid_fields? I also tried 'groups__name' but the result it's always None. Also tried to format it in get_row_str_fields() method, but same error comes.

How it's the correct way to achive this? The only way is with virtual fields?

Dmitri-Sintsov commented 3 years ago

m2m fields are not direcly supported by built-in field serializer. This is due to possibility to have huge number of relations which would cause slow queries and overflow of table grid cells.

Maybe I will add support for m2m cells with query limits to grids in the future, I do not know.

Currently it's possible to use virtual field as the workaround. Please see the examples of virtual fields usage in https://github.com/Dmitri-Sintsov/djk-sample

m2m relations are supported by MultipleKeyGridWidget: https://django-jinja-knockout.readthedocs.io/en/latest/datatables.html#datatables-multiplekeygridwidget

The documentation is for old 1.x version and has not been updated yet for unrelased 2.x version.

Displaying and editing of m2m relations also can be implemented with related grids. Please see ClubEquipmentGrid view / template / js code for one to many example, which may be converted to m2m.

https://github.com/Dmitri-Sintsov/djk-sample/search?q=ClubEquipmentGrid

Dmitri-Sintsov commented 2 years ago

The documentation for MultipleKeyGridWidget is updated and v2.0.0 is released. https://pypi.org/project/django-jinja-knockout/2.0.0/