django-ajax-datatable
django-ajax-datatable copied to clipboard
Suggestion for reverse relationship lookup
It would be really awesome if you can add support for Django reverse relationship lookup. Or if its there, please let me know how to work with it. Thanks
That would be a "1 to many" relation, I guess .. there is a limited support for this, please try (from the example project):
column_defs = [
...,
{'name': 'tags', 'm2m_foreign_field': 'tags__name', 'searchable': True, 'choices': True, 'autofilter': True, },
Say I have some models like:
class main(models.Model):
status= models.CharField(max_length=20)
class Tag(models.Model):
tag1 = models.ForeignKey(main, on_delete=models.CASCADE)
some_name= models.CharField(max_length=20)
# And Other fields
class Tag2(models.Model):
some_field = models.ForeignKey(main, on_delete=models.CASCADE)
# And Other fields
class Tag3(models.Model):
another_field = models.ForeignKey(main, on_delete=models.CASCADE)
# And Other fields
and many more
so if someone wants to present All Tag in one table A reverse relation lookup can help like: main_set
class MainAjaxDatatableView(AjaxDatatableView):
model = main
title = 'Main'
initial_order = [["status", "dec"], ]
length_menu = [[10, -1], [10, 'all']]
column_defs = [
AjaxDatatableView.render_row_tools_column_def(),
{'name': 'Tag_set', 'searchable': True, 'choices': True, 'autofilter': True,}, # Want the some_name field here
# And below will not work becuase the tag field is not in "main" model
{'name': 'tag', 'm2m_foreign_field': 'tag__some_name', 'searchable': True, 'choices': True, 'autofilter': True, },
]
# This will display the data, but search will not work (Both global and column)
def customize_row(self, row, obj):
mod = obj.tag_set.get(tag1=obj)
row['Tag_set'] = mod.some_name
I don't understant this in customize_row()
:
mod = obj.tag_set.get(tag1=obj)
Maybe you need somethig like:
def customize_row(self, row, obj):
tags = obj.tag1_set.all()
row['Tag_set'] = ', '.join([t. some_name for t in tags])
Also, I would remove the classes Tag2 and Tag3 for clarinees: they do not add anything usefull to the test in my opinion
The field name tag1
in the Tag class is misleading, since it contain a reference so the Model main
(should be Main
) and not Tag1
Well, the idea was to get the records through tag1_set while using the main model, and as I said earlier that the data is displayed, but then the search option does not work (Global and Tag_set column) I've tried the below as you suggested earlier:
{'name': 'Tag_set', 'searchable': True, 'choices': True, 'autofilter': True,},
&
# And we know the below will not work obv
{'name': 'Tag1_set', 'm2m_foreign_field': 'tag1__status', 'searchable': True, 'choices': True, 'autofilter': True, },
but it gives the same error that 'Cannot resolve keyword 'Tag_set' into field. Choices are: