Hello everyone,
I’m able to use datatable with one class model by getting json data. However, I would like to add another class with foreign key to models.py. Something like this:
class AnotherModel(models.Model):
description = models.CharField(max_length=256)
ibvs = models.ForeignKey(Ibv, cascede mode on)
How I can arrange json get_data function
and ajax
?
And, I am super confused about json file format & how to pass AnotherModel values to the table.(I’d like to show all models in one table)
MODELS.PY
class Ibv(models.Model):
code = models.CharField(max_length=256)
muestra = models.CharField(max_length=256, null=True, choices=MUESTRAS)
ship = models.CharField(max_length=256)
num = models.CharField(max_length=256)
enc = models.CharField(max_length=256)
obv = models.CharField(max_length=256)
result = models.TextField()
created_at = models.DateField(auto_now=True)
def get_data(self):
return {
'id': self.id,
'code': self.code,
'muestra': self.muestra,
'ship': self.ship,
'num': self.num,
'enc': self.enc,
'obv': self.obv,
'result': self.result,
'created_at': self.created_at,
}
VIEWS.PY
def ibv_json(request):
ibvs = Ibv.objects.all()
data = [ibv.get_data() for ibv in ibvs]
response = {'data': data}
return JsonResponse(response)
BASE.HTML
var table = $('#example').DataTable({
// json to fill the table rows and columns
"ajax": {
url: "/json",
type: "GET"
},
"columns": [
{"data": "id"},
{"data": "code"},
{"data": "muestra"},
{"data": "ship"},
{"data": "num"},
{"data": "enc"},
{"data": "obv"},
// {"data": "result"},
{"data": "created_at"},
Thank you for your help in advance.