Skip to content Skip to sidebar Skip to footer

Create Objects In For Loop

How to create ten User objects? for i in range(11): i = User.objects.create(username = 'test125', email='test@mail.com', password='pass1') Column username is not unique

Solution 1:

You have a unique contraint on the username field which means you cannot have two objects with the same username. Try this:

for i in range(10):
    i = User.objects.create(username = 'testX%s' % i, email='test@mail.com', password='pass1')

Solution 2:

The problem you are having is that you fixed the username value, so you are trying to create 10 users with the same name.

Just use some kind of variation for the username, like username='testuser-{}'.format(i)

Solution 3:

You need to change the name for each record.

You are naming each user "test125". Try concatenating the index for each new record:

for i in range(11):
    i = User.objects.create(username = 'test%s' % i, email='test@mail.com', password='pass1')

Most likely you will need to do the same with your 'email' column:

for i in range(11):
    i = User.objects.create(username = 'test%s' % i, email='test%s@mail.com' % i, password='pass1')

Also, usually is not a good idea to assign your new object to the same variable as your index. Try something different than 'i'.

Post a Comment for "Create Objects In For Loop"