I am trying to render a datatable using django datatables view, but it always gives this error when I try to search,
django.core.exceptions.FieldError: Related Field got invalid lookup: istartswith
.
The model I am using has a ForeignKey to another model.
I have tried all the solutions I have found. They dont work!!
I have tried https://datatables.net/forums/discussion/55916/searching-on-columns-with-data-null ,
https://github.com/izimobil/django-rest-framework-datatables/issues/58
javascript
var customerTable = $(DOMstrings.customerTable ).DataTable({
"processing": true,
"searching": true,
'pageLength': 30,
//"lengthMenu": [ 50, 100, 150, 200 ],
//"colReorder": true,
"scrollY": 500,
//"scrollX": 1500,
//"deferRender": true,
"responsive": true,
"ordering": true,
"paging": true,
"lengthChange": true,
"ajax": {
"url": customerListURL,
},
"serverSide": true,
"columns": [
{ "fields": "id" },
{ "fields": "customer.first_name"},
{ "fields": "amount" },
{ "fields": "date_time" },
//{ "fields": "picture" },
//{ "searchable": "false" },
],
dom: 'Bfrtip',
buttons: [
'colvis',
'pageLength',
],
});
views
class CustomerListJsonView(LoginRequiredMixin, BaseDatatableView):
"""This is the view used by Datatables.net to render the Datatable"""
# The model we're going to show
model = Customer
columns = ['id', 'customer', 'amount', 'date_time']
# This defines columns that will be used in sorting
order_columns = ['id', 'customer', 'amount', 'date_time']
max_display_length = 100
def render_column(self, row, column):
# We want to render phone number as a custom column
if column == 'date_time':
return row.date_time.strftime('%b %d %Y %I:%M %p')
else:
return super(CustomerListJsonView, self).render_column(row, column)
well, i hope my answer will help others since i guess it's too late for this question. I was facing the same problem till i found that i should add in the template data-name attribute refering to the foreign key as follows :
data-name="ForeignKeyModel.ForeignKeyName" then the datatables will send the search statement (icontains or regex) in an acceptable form accepted by django for such fileds!
Check the documentation here : https://django-rest-framework-datatables.readthedocs.io/en/latest/tutorial.html#a-more-complex-and-detailed-example