[Answered ]-Django: Save API data to model

1👍

Better to go with bulk_create instead loop.
try this:

obj_create_list = []
for node in r:
    obj_create_list.append(
       Node(
            cpu=node['cpu'],
            mem=node['mem'],
            node=node['node'],
            status=node['status'],
            )
    )
if obj_create_list:
   Node.objects.bulk_create(obj_create_list)

0👍

Try something below –

Model

class BarList(models.Model):
     api_id = models.CharField(max_length=100, null=False)
     user = models.ForeignKey(User,on_delete=models.CASCADE,null=True,related_name="user")

View

def add_list(request,results):
    if request.method == 'POST':
        Bar = BarList(api_id=results,user=request.user)
        Bar.save()
        return HttpResponseRedirect('/')
    else:
        return render(request, 'API/results.html')

0👍

I think the issue here is not it is creating 3 records in the DB. Because the code you have shared will create three entries in Database, but the variable a will only keep track of last instance which it has created. But if you check like this:

for node in r:
    a = Node(
        cpu=node['cpu'],
        mem=node['mem'],
        node=node['node'],
        status=node['status'],
        )
    a.save()
    print(a)

It should print the all the instances it has created.

Apart from that, what @HemalPatel suggested is the correct appraoch. You should use bulk_create. Also bulk_create has options for updating instances which are suppose to updated (as explained in this answer).

Still, I would suggest that you keep track of all the changes for a specific Node, and you can always get the latest changes. For example using Window function:

from django.db.models import F, Window
from django.db.models.functions import LastValue

nodes= Node.objects.annotate(
    latest_cpu=Window(
        expression=LastValue('cpu'),
        partition_by=['node']
    )
)

nodes.values('node', 'latest_cpu')
👤ruddra

Leave a comment