Datatable multiple models -foreign key with json
Datatable multiple models -foreign key with json
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 very much for help in advance.
This question has an accepted answers - jump to answer
Answers
Looks like you are using Django. There aren't any Django experts on this forum. You will be better served using Stack Overflow or another Django focused forum for questions about combining the models and how to build a JSON response.
Your Django app can return a single level JSON response with the combined models. It will look something like this example. Click on the Ajax tab to see the JSON response. Or you can have nested objects similar to this example. Just depends on your solution needs and how you handle the data in your Django environment.
Kevin
Thank you Kevin! I'm checking other forums and links you shared.