SlideShare a Scribd company logo
Relationships in Django ORM
@starwilly
Outline
• Single model ( Django girls tutorial )
• Relationship
• 1. many-to-one ( )
• 2. many-to-many (Tag)
• What does it looks like in database
• How to define relationship
• Traverse / query / create / delete relation
A Simple Django Model
CRUD (Create, Read, Update, Delete)
Post.objects.create(title='My First Trip',
content=‘ ?',
location=' ')
Post.objects.all()
[<Post: My First Trip>, <Post: My Second Trip>, <Post:
Django >]
Post.objects.filter(pk__gt=1)
[<Post: My Second Trip>, <Post: Django >]
CRUD
posts = Post.objects.filter(pk__lt=3)
[<Post: My First Trip>, <Post: My Second Trip>]
posts.update(location=‘ ')
2
posts.delete()
Model : Table
id title content photo location created_at
1 …
2 …
Relationship
• many-to-one
• many-to-many
Many-to-one Relationship
•
•
• 1.
• 2.
Alan:
Bob:
Cindy:
Model
Many-to-one Relationship
•
PostComment
•
1m
ForeignKey
• (many-to-one)
ForeignKey(othermodel, **options)
Use Foreign Key to Define m:1
Comment Post
id author content
1 Alan …
2 Bob …
3 Cindy …
4 Denny
5
id title content
1 …
2 …
id post_id author content
1 1 Alan …
2 1 Bob …
3 1 Cindy …
4 2 Denny
5 2 Alan
id title content
1 …
2 …
Query m:1 Relationship
id = 1
Alan:
Bob:
Cindy:
Traverse many-to-one relationship
id (pk) = 1
post1 = Post.objects.get(pk=1)
comments = Comment.objects.filter(post_id=1)
comments = Comment.objects.filter(post=post1)
[<Comment: Alan: >, <Comment: Bob: >, <Comment:
Cindy: >]
Traverse many-to-one relationship
id (pk) = 1
post1 = Post.objects.get(pk=1)
comments = post1.comment_set.all()
<Model>_set
[<Comment: Alan: >, <Comment: Bob: >, <Comment:
Cindy: >]
Associate Post and Comment
post = Post.objects.get(pk=1)
comment = Comment(author=‘Billy’,
content=‘hi’)
post.comment_set.add(comment)
Remove Comment from Post
post1 = Post.objects.get(pk=1)
post1.comment_set.all()
[<Comment: Alan: >, <Comment: Bob: >, <Comment:
Cindy: >]
c = Comment.objects.get(pk=1)
<Comment: Alan: >
c.delete()
post.comment_set.all()
[<Comment: Bob: >, <Comment: Cindy: >]
ForeignKey.related_name
comment_list = post.comment_set.all()
comment_list = post.comments.all()
Foreign Key
• (many-to-one relationship)
• <model>_set
• related_name
• add()
Many-to-many Relationships
Tag
myblog.com/post/1 myblog.com/tag/food
What is Many-to-many Relationship
Post Tag
• tag
• tag
n m
Tag Model
SlugField
• CharField
• (hyphen)
•
• myblog.com/tags/ (X)
• myblog.com/tags/food (O)
• myblog.com/posts/[ ] (X)
• myblog.com/posts/a-wonderful-trip-in-japan (O)
Tag Table
id name slug
1 food
2 japan
3 taiwan-north
4 taipei
… …
taipei
id title content
1 …
2 …
Post
Tag
, ,
id name slug
1 food
2 japan
3 taiwan-north
4 taipei
… …
id title content tags
1 … 1, 3, 4
2 … 2
Post
Tag
, ,
id name slug
1 food
2 japan
3 taiwan-north
4 taipei
… …
id title content
1 …
2 …
Post
Tag
, ,
id name slug
1 food
2 japan
3 taiwan-north
4 taipei
… …
id post_id tag_id
1 1 1
2 2 2
3 1 3
4 1 4
ManyToManyField
ManyToManyField(othermodel, **options)
tags = models.ManyToManyField('Tag', blank=True)
ManyToManyField
•
• Django m2m
ManyToManyField(othermodel, **options)
id title content
1 …
2 …
id name slug
1 food
2 japan
… … …
id post_id tag_id
1 1 1
2 2 2
3 1 3
4 1 4
Query M2M Relationship
from trips.models import Post, Tag
post1 = Post.objects.get(pk=1)
<Post: >
post1.tags.all()
[<Tag: >, <Tag: >]
Query M2M Relationship
from trips.models import Post, Tag
tag_food = Tag.objects.get(pk=1)
<Tag: >
tag_food.post_set.all()
[<Post: >]
ManyToManyField.related_name
tag_food = Tag.objects.get(pk=1)
tag_food.post_set.all()
tag_food.posts.all()
Create M2M Relationship
from trips.models import Post, Tag
post1 = Post.objects.get(pk=1)
tag_japan = Tag.objects.create(name=‘ ’,
slug=‘japan’)
tag_food = Tag.objects.get(slug=‘food’)
post1.tags.add(tag_japan)
tag_food.post_set.add(post1)
Remove M2M Relationship
from trips.models import Post, Tag
tag_japan = Tag.objects.get(slug=‘japan’)
post1 = Post.objects.get(pk=1)
post1.tags.remove(tag_japan)
tag_japan.post_set.remove(post1)
Filter M2M Relationship
from trips.models import Post, Tag
tag_japan = Tag.objects.get(slug=‘japan’)
tag_food = Tag.objects.get(slug=‘food’)
tag_japan.post_set.all()
# [<Post: >]
Post.objects.filter(tags=tag_japan)
# [<Post: >]
Post.objects.filter(tags__in=[tag_japan, tag_food])
#[<Post: >, <Post: >]
ManyToManyField
•
• Table (Mapping)
• releated_name
• add() , remove()
• https://docs.djangoproject.com/en/1.9/ref/models/relations/
Get your hand dirty
• Tag
• Tag
•
• Tag
• Tag Tag
Tips:
djangogirls/mysite/templates/post.html
Tips: Tag
djangogirls/mysite/templates/post.html
Tips: Tag
url(r'^tag/(?P<slug>[w-]+)/$', tag_detail, name='tag_detail'),
djangogirls/mysite/trips/views.py
djangogirls/mysite/templates/tag.html

More Related Content

Similar to Relationships in Django ORM

WordPress Tips and Tricks (DFW Meetup)
WordPress Tips and Tricks (DFW Meetup)WordPress Tips and Tricks (DFW Meetup)
WordPress Tips and Tricks (DFW Meetup)Stephanie Leary
 
Learning How To Use Jquery #5
Learning How To Use Jquery #5Learning How To Use Jquery #5
Learning How To Use Jquery #5
Takahiro Yoshimura
 
Demystifying WordPress Conditional Tags
Demystifying WordPress Conditional TagsDemystifying WordPress Conditional Tags
Demystifying WordPress Conditional Tags
WP Pittsburgh Meetup Group
 
Jumpstart Django
Jumpstart DjangoJumpstart Django
Jumpstart Django
ryates
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
 
ActiveRecord vs Mongoid
ActiveRecord vs MongoidActiveRecord vs Mongoid
ActiveRecord vs Mongoid
Ivan Nemytchenko
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
Qiangning Hong
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
rogerbodamer
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
Robert Lujo
 
Dojo Confessions
Dojo ConfessionsDojo Confessions
Dojo Confessions
Rebecca Murphey
 
Meta tag creation
Meta tag creationMeta tag creation
Meta tag creation
AniketTiwari26
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
Christopher Adams
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
Damien Seguy
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDB
rogerbodamer
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsMark Rackley
 
What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)
Stephanie Leary
 
WordPress Hidden Gems (July 2011)
WordPress Hidden Gems (July 2011)WordPress Hidden Gems (July 2011)
WordPress Hidden Gems (July 2011)Stephanie Leary
 
Benefits of using MongoDB: Reduce Complexity & Adapt to Changes
Benefits of using MongoDB: Reduce Complexity & Adapt to ChangesBenefits of using MongoDB: Reduce Complexity & Adapt to Changes
Benefits of using MongoDB: Reduce Complexity & Adapt to ChangesAlex Nguyen
 
Oren rubin statistical element locator
Oren rubin   statistical element locatorOren rubin   statistical element locator
Oren rubin statistical element locator
PractiTest
 

Similar to Relationships in Django ORM (20)

WordPress Tips and Tricks (DFW Meetup)
WordPress Tips and Tricks (DFW Meetup)WordPress Tips and Tricks (DFW Meetup)
WordPress Tips and Tricks (DFW Meetup)
 
Learning How To Use Jquery #3
Learning How To Use Jquery #3Learning How To Use Jquery #3
Learning How To Use Jquery #3
 
Learning How To Use Jquery #5
Learning How To Use Jquery #5Learning How To Use Jquery #5
Learning How To Use Jquery #5
 
Demystifying WordPress Conditional Tags
Demystifying WordPress Conditional TagsDemystifying WordPress Conditional Tags
Demystifying WordPress Conditional Tags
 
Jumpstart Django
Jumpstart DjangoJumpstart Django
Jumpstart Django
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
ActiveRecord vs Mongoid
ActiveRecord vs MongoidActiveRecord vs Mongoid
ActiveRecord vs Mongoid
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
Dojo Confessions
Dojo ConfessionsDojo Confessions
Dojo Confessions
 
Meta tag creation
Meta tag creationMeta tag creation
Meta tag creation
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDB
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentials
 
What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)What's New in WordPress 3.0 (for developers)
What's New in WordPress 3.0 (for developers)
 
WordPress Hidden Gems (July 2011)
WordPress Hidden Gems (July 2011)WordPress Hidden Gems (July 2011)
WordPress Hidden Gems (July 2011)
 
Benefits of using MongoDB: Reduce Complexity & Adapt to Changes
Benefits of using MongoDB: Reduce Complexity & Adapt to ChangesBenefits of using MongoDB: Reduce Complexity & Adapt to Changes
Benefits of using MongoDB: Reduce Complexity & Adapt to Changes
 
Oren rubin statistical element locator
Oren rubin   statistical element locatorOren rubin   statistical element locator
Oren rubin statistical element locator
 

Recently uploaded

Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETSHidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Kamil Uğraş TÜRKOĞLU
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
pandeypratikwgblindi
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
flyn goo
 
Wayanad-The-Touristry-Heaven to the tour.pptx
Wayanad-The-Touristry-Heaven to the tour.pptxWayanad-The-Touristry-Heaven to the tour.pptx
Wayanad-The-Touristry-Heaven to the tour.pptx
cosmo-soil
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
RezStream
 
在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样
在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样
在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样
v6ldcxuq
 
Assessing the Influence of Transportation on the Tourism Industry in Nigeria
Assessing the Influence of Transportation on the  Tourism Industry in NigeriaAssessing the Influence of Transportation on the  Tourism Industry in Nigeria
Assessing the Influence of Transportation on the Tourism Industry in Nigeria
gsochially
 

Recently uploaded (7)

Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETSHidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
Hidden Gems of Europe - DISCOVERING THE CONTINENT'S BEST-KEPT SECRETS
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
 
Wayanad-The-Touristry-Heaven to the tour.pptx
Wayanad-The-Touristry-Heaven to the tour.pptxWayanad-The-Touristry-Heaven to the tour.pptx
Wayanad-The-Touristry-Heaven to the tour.pptx
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
 
在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样
在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样
在线办理(BU毕业证书)波士顿大学毕业证录取通知书一模一样
 
Assessing the Influence of Transportation on the Tourism Industry in Nigeria
Assessing the Influence of Transportation on the  Tourism Industry in NigeriaAssessing the Influence of Transportation on the  Tourism Industry in Nigeria
Assessing the Influence of Transportation on the Tourism Industry in Nigeria
 

Relationships in Django ORM