How to Render Django ForeignKey relation on Datatables Serverside

Viewed 509

Im stuck for days, im using this plugin django-datatables-view and I need to render ForeignKey related value in serverside datatables, it's like: {{data.pasien_id.name}} in typical django template. but that way not work with serverside datatables, and there is no documentation anywhere to achieve that. the code shown below.

Models.py

class Pasien(models.Model):
    nama = models.CharField(max_length=40, null=True)
 
class Log_book(models.Model):
    pasien = models.ForeignKey(Pasien, on_delete=models.PROTECT, null=True)

Views.py

 class logbook_json(BaseDatatableView):
    model = Log_book
    columns = ['id', 'pasien_id']
    order_columns = ['id','pasien_id']
    
  def render_column(self, row, column):
        if column == 'id':
            return escape('{0}'.format(row.id))
        else:
            return super(logbook_json, self).render_column(row, column)

    def filter_queryset(self, qs):
        filter_customer = self.request.GET.get('search[value]', None)
        if filter_customer:
            customer_parts = filter_customer.split(' ')
            qs_params = None
            for part in customer_parts:
                q = Q(id__icontains=part) | Q(pasien_id__icontains=part)
                qs_params = qs_params | q if qs_params else q
            qs = qs.filter(qs_params)
        return qs

templates.html datatables load,

<script class="init" type="text/javascript">
    $(document).ready(function () {
        $('#responsive-datatablex').DataTable({
        // ...
        searching: true,
        processing: true,
        serverSide: true,
        stateSave: true,
        "ajax": "{% url 'logbook_json' %}",
    });
    });
</script>
1 Answers

It's easier if you get your JSON to return in a flat structure (rather than nested):

{
"name": name,
"id": id
}

Then you need to define data for the column to read values from the JSON. This can be quite tricky so it pays to read the documentation carefully.

You must define your datatables column correctly so that it can read this data. Note that there are "orthogonal" data types (ie. for sorting, display etc):

columns: [
{
  "title": "Name",
  "data": "name",
  "render": {
      "_": "name",
  },
  "searchable": true,
  "orderable": true,
  "defaultContent": "N/A"
}
]

There are other ways of achieving the same, so refer to the docs. The key thing is that the DataTables column definition must match what is returned in the JSON.

Some tips:

  1. Try to get one column working by itself first.

  2. Load the JSON in a separate tab so that you can see that it is being rendered correctly. Note that there are some specific rules about rendering the serverside response, I expect that django-datatables-view honours these but I haven't checked.

Related