[Answer]-Django โ€“ Inserting data into a many to many relationship model with unique constraint

1๐Ÿ‘

โœ…

You should do something like this:

for s in cleaned_skills:
    skill = Skill.objects.get_or_create(title=s)
    user_profile.skill.add(skill)

That will only create the skill if a skill with that same title does not already exist. It then adds the skill to the user.

EDIT: you could save a few queries, if you do a bulk_create. Something like this:

skill_titles = Skill.objects.values_list('title', flat=True)
new_skills = Skill.objects.bulk_create([Skill(title=s) for s in cleaned_skills if s not in skill_titles])
user_profile.skill.add(*new_skills)
๐Ÿ‘คjproffitt

Leave a comment