简体   繁体   中英

Django: Key (slug)=(*) already exists

I'm pretty new to Django and python and I'd like to learn more about how to populating my Postgres database.

Here is my current model: models.py

from django.template.defaultfilters import slugify

class Skill(models.Model):
    name = models.TextField()
    slug = models.TextField(unique = True)
    def __unicode__(self):
        return "%s" % self.name

and my views: views.py

r = r.json()

try:
    Skills = r['data']['skills']
except:
    pass

for skill in Skills:
    skill = Skill.objects.create(name=skill['name'],slug=slugify(skill['name']))

I'm getting the error: Exception Type: IntegrityError

DETAIL: Key (slug)=(systems-engineering) already exists.

I've been reading a similar post although still haven't been able to solve my problem. objects.create() will shows an error when the object already exists in the database, but I was getting error with the code above. Could "unique = True" be causing the error? and how do you fix this?

Follow up

My problem is simpler than I thought. I was able to run psql interactive terminal and see my data populating. I wasn't able to see it on the admin site because I missed out registering the models on admin.py

When you provide unique=True , the field will be unique throughout the table. Hence, when you try to add a data which is already in DB, it will raise an error. See this official doc for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM