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
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)
CodePudding user response:
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()