tVoss
tVoss

Reputation: 71

How to implement Django multiple choice of foreign key

Here's the scenario. The actual object names are tweaked, but this is the idea. Let's say I have a color model

class Color(models.Model):
    name = models.CharField(max_length=20)

And I also have a User model

class User(models.Model):

What I want to do is allow the user to choose multiple colors as their favorites. Is there a way to properly store multiple colors in the single user model?

The best idea I have is having an additional model that looks like this:

class UserMCColor(models.Model):
    user = models.ForeignKey('User')
    color = models.ForeignKey('color')

And add an entry to that table for every favorite color chosen, then just grab the rows based of the User id. Is this the best way to go about it?

Upvotes: 0

Views: 3827

Answers (1)

mconlin
mconlin

Reputation: 8733

You will need a many to many relationship. A user can have many favorite colors and a color can belong to many users.

https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/

color = models.ManyToManyField(User)

Upvotes: 6

Related Questions