zallarak
zallarak

Reputation: 5515

Django - Need some guidance on how to implement a ManyToMany database

I want the ability to let users indicate what countries they have visited.. my models.py looks something like this:

class User(models.Model):
      name = models.CharField(max_length=50)
      countries = models.ManyToManyField(Countries)

class Countries(models.Model):
      #This is where I don't know what to do.
      #The end goal is for the user to be able to check off what countries he/she has visited

Upvotes: 2

Views: 91

Answers (3)

jlarry
jlarry

Reputation: 430

You would create the relationship the other way around

 class User(models.Model):
     name = models.CharField(max_length=50)

 class Countries(models.Model):
     user = models.ForeignKey(User)

If you are using django's built in User stuff then you only need this.

from django.contrib.auth.models import User

class Countries(models.Model):
    user = models.ForeignKey(User)

Upvotes: 2

fish2000
fish2000

Reputation: 4435

You're fine as is w/r/t the ManyToManyField.

Now you'll want to create a form for this model to allow the checking-off to be done by your users.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Relation fields already generate an attribute on the other model for the reverse relation unless explicitly disabled.

Upvotes: 1

Related Questions