Skip to content

Instantly share code, notes, and snippets.

@zurfyx
Created April 22, 2016 18:54
Show Gist options
  • Save zurfyx/e4dcd93d418cdaf3cc805086b290dbc8 to your computer and use it in GitHub Desktop.
Save zurfyx/e4dcd93d418cdaf3cc805086b290dbc8 to your computer and use it in GitHub Desktop.

DJANGO MODEL TYPES

One to One

More information about a Model (only one fits the model extending it)

Example (Car -> Engine)

class Car(models.Model):
	engine = models.OneToOneField(Engine)

Foreign key

More information about a Model (but this extra information might have to be used as well for other models). Also applies to several tuple information related to the Model.

Example (Car -> Manufacturer) (Comments -> Post)

class Car(models.Model):
	manufacturer = models.ForeignKey(Manufacturer)

Many to Many

Your model can be related to several models. But, these several models can be related to several of Your model as well.

Example (Post <-> Tag)

class Tag(models.Model):
	posts = models.ManyToMany(Post, related_name='tags')

Many to Many (through)

Same as Many to Many. But this time you can have a custom intermediate table. This means you can add extra information to the relation.

Example (Project <- Role -> User)

class User(models.Model):
	project = model.ManyToManyField(Project, through='Role')

class Role(models.Model):
	user = models.ForeignKey(User)
	project = models.ForeignKey(Project)
	role = models.IntegerField()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment