Darwin Tech
Darwin Tech

Reputation: 18919

Django: update two models at once

I have two Django models like so:

class Skill(models.Model):
    title = models.CharField(max_length=255)

    def __unicode__(self):
        return self.title


class UserSkills(models.Model):
    user = models.ForeignKey(User)
    skill = models.ManyToManyField(Skill)

    def __unicode__(self):
        return '%s | %s' % (self.user, self.skill)

Now, I have lists of skills associated with a user which I want to simultaneously update the Skills model and the User's associated skills. Something like:

# cleaned_skills[] is list if unicode strings

for skill in cleaned_skills:
    s, created = Skill.objects.get_or_create(title=skill)
    s.save()
    u, created = UserSkills.objects.get_or_create(skill=s, user=request.user)
    u.save()

For some reason this doesn't feel right to me. Is there some way I should update both the Skill and the User models at the same time?

Upvotes: 0

Views: 1101

Answers (1)

Seyeong Jeong
Seyeong Jeong

Reputation: 11028

Personally, I think you're doing it correctly.

Upvotes: 1

Related Questions