user764529
user764529

Reputation:

ManyToManyField in django

I have the following model:

class Position(models.Model):
    label = models.CharField(max_length=100)

class UserProfile(models.Model):
    location = models.CharField(max_length=100, blank=True)
    positions = models.ManyToManyField(Position)

How would I enter the following two statements correctly?

-- UserpProfile.objects.create(location = 'usa', positions = 'artist')
-- UserProfile.objects.create(location = 'usa', positions = 'artist', 'programmer', and 'teacher')

Note: I do not want to provide values for the user to choose from. I only want them to be able to enter multiple positions, and then to store those multiple positions in the table.

Upvotes: 0

Views: 208

Answers (1)

Tim Yates
Tim Yates

Reputation: 5291

Off the top of my head, I'm not sure if list assignment works in a constructor, but you can assign it this way:

 profile = UserProfile(location='usa')
 profile.positions = ['artist', 'programmer', 'teacher']

Upvotes: 1

Related Questions