django.db.utils.IntegrityError:UNIQUE约束失败:auth_user.username

时间:2017-02-07 16:44:23

标签: python django django-models

我有一个具有以下属性的Organization类:

class Organisation(models.Model):
    user = models.OneToOneField(User, null=True)
    phoneNumber = models.CharField(max_length=12)
    description = models.CharField(max_length=1024)
    image = models.ImageField(upload_to='organisation_image')
    category = models.ForeignKey("Category")
    subscribedVolunteers = models.ManyToManyField(Volunteer)

    def __unicode__ (self):
        return self.name

我想用这个文件填充数据库:

def populate():
    organisations = [
        {"first_name":"Concrete Garden","description":description,
         "email":"info@concretegarden.org.uk",
         "password":"cgarden",
         "username":"cgarden",
         "phoneNumber":"0141 237 9144",
         "category":categories_arr[0]}
        }

    organisations_arr = []
    for org in organisations:
        organisations_arr.append(add_organisation(org))

def add_organisation(org):
    print(org["username"])
    #ERROR HERE - when trying to create user object
    u = User.objects.create_user(username=org["username"], email=org["email"], first_name=org["first_name"],last_name=org["first_name"], password=org["password"])
    u.save()
    c = Organisation.objects.get_or_create(user=u,phoneNumber=org["phoneNumber"],description=org["description"],category=org["category"])[0]
    c.save()
    return c

if __name__ == '__main__':
    print("Starting population script...")
    populate()

非常感谢任何评论或建议。谢谢。

1 个答案:

答案 0 :(得分:0)

您已经有一个'cgarden'条目作为数据库中User的用户名。这就是错误信息的含义 您可以使用Django shell查询数据库。我建议使用数据库浏览工具(可能在您的IDE中)以使事情变得更容易。