Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fill my database as I go with data from an API – Django Prject

I would like to fill my database as I go with data from an API that I use that sends me data users.

Here when a user already exists and we just modify his information at the API level, then I would just like to apply the modify the information not duplicate the user, and if he does not exist in my database I will create.
But every time I call the API, if the user already existed in my database, it creates it again (duplicate) and I don’t want this side

Note that I retrieve user data in the form of a dictionary

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please where is the problem

views.py

from .models import Utilisateur

url='http://userAPI/Users/GetUsers'
y=requests.get(url)
users=y.json()
all_users=users['user']
for one_user in all_users:
   user=Utilisateur(name=one_user['name'],adresse=one_user['adresse'],code=one_user['code'])
   user.save()

models.py

from django.db import models

class Utilisateur(models.Model):
  name=models.CharField(max_length=100)
  adresse=models.CharField(max_length=255,blank=True,null=True)
  code=models.CharField(max_length=10)

>Solution :

You use a unique field, like name, and use it in a get_or_create call:

for one_user in all_users:
    user = Utilisateur.objects.get_or_create(name=one_user['name'])
    user.adresse=one_user['adresse']
    user.code=one_user['code']
    user.save()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading