1

i'm trying to import users in database using bulk create but i'm getting exception ValueError: Field 'id' expected a number but got nan.

I'm getting exception when bulk create profiles.

def import_users(csv_file):
    df = pd.read_csv(io.StringIO(csv_file.decode('utf-8')))
    users = []
    profiles = []

    for index, row in df.iterrows():
        user = User()
        user.username = row['username']
        user.password = make_password(str(row['password']))
        user.first_name = row['firstname']
        user.last_name = row['lastname']
        user.is_active = True
        user.email = row.get('email', None)

        user.profile = Profile()
        user.profile.app_id = row['app_id']
        user.profile.company_id = row['company_id']

        user.profile.user = user
        users.append(user)
        profiles.append(user.profile)

    try:
        users = User.objects.bulk_create(users, ignore_conflicts=False)
    except Exception as e:
        LOGGER.exception(str(e))

    try:
        Profile.objects.bulk_create(profiles, ignore_conflicts=False)
    except Exception as e:
        LOGGER.exception(str(e))

Model for Profile is:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company = models.ForeignKey(to='Company', on_delete=models.SET_NULL, null=True)
    app = models.ForeignKey(to='App', default=1000, on_delete=models.SET_DEFAULT, null=False)

I checked this solution on SO, but no help for me.

Stefan
  • 157
  • 2
  • 12
  • 1
    Hello my friend, this error is probably because of the value passed for 'app_id' or 'company_id', check the csv file it must be a null value some where, or to catch null values in python script use -> if is none like here https://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none – Luiz Oct 09 '21 at 19:52
  • Yes, when i read csv data, i got float (nan) instead of null (None) value. – Stefan Oct 10 '21 at 12:41

0 Answers0