SlideShare une entreprise Scribd logo
1  sur  40
Django Meetup:
Django Multicolumn Joins
Jeremy Tillman
Software Engineer, Hearsay Social
@hssengineering
Django Multicolumn Joins | © 2012 Hearsay Social 2
About Me
• Joined Hearsay Social May 2012 as Software Engineering Generalist
• Computer Engineer BA, Purdue University
• 3 years @ Microsoft working on versions of Window Server
• 9 years of databases experience
– Access, SQL Server, MySql
• Loves Sea Turtles!
Django Multicolumn Joins | © 2012 Hearsay Social 3
Why do we want multicolumn joins?
Django Multicolumn Joins | © 2012 Hearsay Social 4
Django First App: Poll example
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Django Multicolumn Joins | © 2012 Hearsay Social 5
What if we stored Polls for X number of customers?
class Customer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = („name‟,)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
class Poll(models.Model):
customer = models.ForeignKey(Customer)
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
CREATE TABLE customer(
id INT NOT NULL AUTO_INCRMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL);
CREATE TABLE poll(
id INT NOT NULL AUTO_INCRMENT PRIMARY KEY,
customer_id INT NOT NULL,
question VARCHAR(200) NOT NULL,
pub_date DATETIME NOT NULL,
INDEX idx_customer (customer_id));
CREATE TABLE choice(
id INT NOT NULL AUTO_INCRMENT PRIMARY KEY,
poll INT NOT NULL,
choice_text VARCHAR (200),
votes INT NOT NULL DEFAULT 0,
INDEX idx_poll (poll_id));
Django Multicolumn Joins | © 2012 Hearsay Social 6
How is our data being stored?
CREATE TABLE choice(
id INT NOT NULL AUTO_INCRMENT PRIMARY KEY,
poll_id INT NOT NULL,
choice_text VARCHAR (200),
votes INT NOT NULL DEFAULT 0,
INDEX idx_poll (poll_id));
id poll_id choice_text votes
1 1 Ham 5
2 7 Aries 8
3 2 Elephant 9
…. … … …
23,564,149 1 All of the above 2
23,564,150 74 Sea turtle 7
Django Multicolumn Joins | © 2012 Hearsay Social 7
Data locality part 1: Scope by poll
CREATE TABLE choice(
id INT NOT NULL,
poll_id INT NOT NULL,
choice_text VARCHAR (200),
votes INT NOT NULL DEFAULT 0,
PRIMARY KEY (poll_id, id));
id poll_id choice_text votes
1 1 Ham 5
1,562 1 Turkey 46
23,564,149 1 All of the above 2
…. … … …
18,242,234 74 Jelly fish 0
23,564,150 74 Sea turtle 7
Django Multicolumn Joins | © 2012 Hearsay Social 8
Data locality part 2: Scope by customer
CREATE TABLE choice(
id INT NOT NULL,
customer_id INT NOT NULL,
poll_id INT NOT NULL,
choice_text VARCHAR (200),
votes INT NOT NULL DEFAULT 0,
PRIMARY KEY (customer_id, poll_id, id));
id poll_id customer_id choice_text votes
1 1 1 Ham 5
1,562 1 1 Turkey 46
23,564,149 1 1 All of the above 2
18,242,234 74 1 Jelly fish 0
23,564,150 74 1 Sea turtle 7
… … … … …
Django Multicolumn Joins | © 2012 Hearsay Social 9
Representation in Django Models
class Customer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = („name‟,)
class Choice(models.Model):
customer = models.ForeignKey(Customer)
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
class Poll(models.Model):
customer = models.ForeignKey(Customer)
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Django Multicolumn Joins | © 2012 Hearsay Social 10
Customer Load/Data Balance
customer_id id
1 1
2 2
3 3
4 4
Django Multicolumn Joins | © 2012 Hearsay Social 11
Customer Load/Data Balance: Split Customers
customer_id id
3 3
3 5
4 4
4 6
customer_id id
1 1
1 5
2 2
2 6
Django Multicolumn Joins | © 2012 Hearsay Social 12
Add DB and Balance Load: id collision
customer_id id
3 3
3 5
customer_id id
1 1
1 5
customer_id id
2 2
2 6
4 4
4 6
Django Multicolumn Joins | © 2012 Hearsay Social 13
Queries: Find all choices for a poll?
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 14
Queries: Find all choices for a poll?
Attempt 1) Using related set
target_poll.choice_set.all()
or
Choice.objects.filter(poll=target_poll)
SELECT * FROM choice WHERE poll_id = 1
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 15
Queries: Find all choices for a poll?
Attempt 2) Adding a F expression
target_poll.choice_set.all(customer=F(„poll__customer‟))
or
Choice.objects.filter(poll=target_poll,
customer=F(„poll__customer‟))
SELECT c.* FROM choice c INNER JOIN poll p
ON c.poll_id = p.id
WHERE
c.poll_id = 1
AND
c.customer_id = p.customer_id;
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 16
Queries: Find all choices for a poll?
Attempt 3) Filter explicitly
target_poll.choice_set.all(customer=target_poll.customer)
or
Choice.objects.filter(poll=target_poll,
customer=target_poll.customer)
SELECT * FROM choice
WHERE
poll_id = 1
AND
customer_id = 2;
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 17
Field Assignment
quantity_inn = Customer.objects.create(id=15, name=„Quantity Inn‟)
quantity_poll = Poll.objects.create(id=1, company=quantity_inn, question=„What size bed do you prefer?‟)
choice1 = Choice(id=1, choice_text=“King”, poll=quantity_poll)
choice1.customer_id ??????  
choice1.customer = quantity_poll.customer Repetitive
Django Multicolumn Joins | © 2012 Hearsay Social 18
What do we do?
Django Multicolumn Joins | © 2012 Hearsay Social 19
Solution via Django 1.6
class ForeignObject(othermodel, from_fields, to_fields[, **options])
where:
from django.db.models import ForeignObject
Django Multicolumn Joins | © 2012 Hearsay Social 20
ForeignObject Usage
class ForeignModel(models.Model):
id1 = models.IntegerField()
id2 = models.IntegerField()
class ReferencingModel(models.Model):
om_id1 = models.IntegerField()
om_id2 = models.IntegerField()
om = ForeignObject(ForeignModel,
from_fields=(om_id1, om_id2),
to_fields=(id1, id2))
Django Multicolumn Joins | © 2012 Hearsay Social 21
Conversion from ForeignKey to ForeignObject
class Choice(models.Model):
customer = models.ForeignKey(Customer)
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
class Choice(models.Model):
customer = models.ForeignKey(Customer)
poll_id = models.IntegerField()
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
poll = models.ForeignObject(Poll,
from_fields=(‘customer’, ‘poll_id’),
to_fields=(‘customer’, ‘id’))
Django Multicolumn Joins | © 2012 Hearsay Social 22
Queries with ForeignObject
Attempt 1) Using related set
target_poll.choice_set.all()
SELECT * FROM choice
WHERE
poll_id = 1
AND
customer_id = 2;
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 23
Queries with ForeignObject
Attempt 2) Manually stated
Choice.objects.filter(poll=target_poll)
SELECT * FROM choice
WHERE
poll_id = 1
AND
customer_id = 2;
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 24
Queries with ForeignObject
Attempt 2) Manually stated w/tuple
Choice.objects.filter(poll=(2, 1))
SELECT * FROM choice
WHERE
poll_id = 1
AND
customer_id = 2;
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 25
Field Assignment with ForeignObject
quantity_inn = Customer.objects.create(id=15, name=„Quantity Inn‟)
quantity_poll = Poll.objects.create(id=1, company=quantity_inn, question=„What size bed do you prefer?‟)
choice1 = Choice(id=1, choice_text=“King”, poll=quantity_poll)
choice1.customer_id
>> 15  
choice1.customer = quantity_poll.customer  Not needed
Django Multicolumn Joins | © 2012 Hearsay Social 26
“With great power comes great responsibility”
Django Multicolumn Joins | © 2012 Hearsay Social 27
Tuple ordering matters
Choice.objects.filter(poll=(1, 2))
SELECT * FROM choice
WHERE
poll_id = 2
AND
customer_id = 1;
poll = models.ForeignObject(Poll,
from_fields=(‘customer’, ‘poll_id’),
to_fields=(‘customer’, ‘id’))
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 28
IN Operator
Choice.objects.filter(poll__in=[(2, 1), (2, 2)])
SELECT * FROM choice
WHERE
(poll_id = 1
AND
customer_id = 2)
OR
(poll_id = 2
AND
customer_id = 2);
poll = models.ForeignObject(Poll,
from_fields=(‘customer’, ‘poll_id’),
to_fields=(‘customer’, ‘id’))
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 29
IN Operator w/queryset
Choice.objects.filter(poll__in=
Poll.objects.filter(customer_id=2))
SELECT c.* FROM choice c
WHERE
EXISTS (SELECT p.customer_id, p.id
FROM poll p
WHERE
p.customer_id = 2
AND
p.customer_id = c.customer_id
AND
p.id = c.poll_id);
poll = models.ForeignObject(Poll,
from_fields=(‘customer’, ‘poll_id’),
to_fields=(‘customer’, ‘id’))
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 30
IN Operator with MySql
Choice.objects.filter(poll__in=[(2, 1), (2, 2)])
SELECT * FROM choice
WHERE
(poll_id, customer_id)
IN
((1, 2), (2, 2));
poll = models.ForeignObject(Poll,
from_fields=(‘customer’, ‘poll_id’),
to_fields=(‘customer’, ‘id’))
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 31
IN Operator w/queryset & MySQL
Choice.objects.filter(poll__in=
Poll.objects.filter(customer_id=2))
SELECT c.* FROM choice c
WHERE
(c.customer_id, c.poll_id)
IN
(SELECT p.customer_id, p.id
FROM poll p
WHERE
p.customer_id = 2);
poll = models.ForeignObject(Poll,
from_fields=(‘customer’, ‘poll_id’),
to_fields=(‘customer’, ‘id’))
customer_id id question
1 1 What’s your seat pref.?
1 2 Are you married?
2 1 Gender?
2 2 Did you have fun?
customer_id poll_id id choice_text
1 1 1 Window
1 1 2 Ailse
1 2 1 Yes
1 2 2 No
2 1 1 Male
2 1 2 Female
2 2 1 Yes?
Poll
Choice
Django Multicolumn Joins | © 2012 Hearsay Social 32
ForeignKey vs ForeignObject
Whats the difference?
ForeignKey is a ForeignObject
pseudo def: ForeignObject(OtherModel, from_fields=((„self‟,)), to_fields=((OtherModel._meta.pk.name),))
Django Multicolumn Joins | © 2012 Hearsay Social 33
ForeignKey usage: Order By Example
Poll.objects.order_by(„customer‟)
class Customer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = („name‟,)
class Poll(models.Model):
customer = models.ForeignKey(Customer)
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Django Multicolumn Joins | © 2012 Hearsay Social 34
ForeignKey usage: Order By Example
Poll.objects.order_by(„customer‟)
SELECT p.* from poll INNER JOIN customer c
ON
p.customer_id = c.id
ORDER BY
c.name ASC;
class Customer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = („name‟,)
class Poll(models.Model):
customer = models.ForeignKey(Customer)
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Django Multicolumn Joins | © 2012 Hearsay Social 35
ForeignKey usage: Order By Example
Poll.objects.order_by(„customer_id‟)
SELECT p.* from poll INNER JOIN customer c
ON
p.customer_id = c.id
ORDER BY
c.name ASC;
class Customer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = („name‟,)
class Poll(models.Model):
customer = models.ForeignKey(Customer)
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Alias for customer
Django Multicolumn Joins | © 2012 Hearsay Social 36
ForeignKey usage: Order By Example
Poll.objects.order_by(„customer__id‟)
SELECT p.* from poll INNER JOIN customer c
ON
p.customer_id = c.id
ORDER BY
p.customer_id ASC;
class Customer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = („name‟,)
class Poll(models.Model):
customer = models.ForeignKey(Customer)
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Django Multicolumn Joins | © 2012 Hearsay Social 37
ForeignKey usage: Order By Example
Poll.objects.order_by(„customer_id‟)
SELECT * from poll
ORDER BY
customer_id ASC;
class Customer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = („name‟,)
class Poll(models.Model):
customer_id = models.IntegerField()
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
customer = models.ForeignObject(Customer,
from_fields=(„customer_id‟,),
to_fields=(„id‟,))
Django Multicolumn Joins | © 2012 Hearsay Social 38
Still more fun stuff
• ForeignObject.get_extra_description_filter
• ForeignObject.get_extra_restriction
• More to come
Django Multicolumn Joins | © 2012 Hearsay Social 39
Dig for more information:
• ForeignObject source
• django/db/models/fields/related.py
• V1 Version of Patch (Based of Django 1.4)
• https://github.com/jtillman/django/tree/MultiColumnJoin
• Blog post to come
• Hearsay Social Blog (http://engineering.hearsaysocial.com/)
Django Multicolumn Joins | © 2012 Hearsay Social 40
Questions?

Contenu connexe

Similaire à Django Multicolumn Joins: Data Locality and Foreign Keys

Surveys That Work: using questionnaires to gather useful data, Seattle 2010
Surveys That Work: using questionnaires to gather useful data, Seattle 2010Surveys That Work: using questionnaires to gather useful data, Seattle 2010
Surveys That Work: using questionnaires to gather useful data, Seattle 2010Caroline Jarrett
 
The UX of AI Matters : How does the visual representation of a recommendation...
The UX of AI Matters : How does the visual representation of a recommendation...The UX of AI Matters : How does the visual representation of a recommendation...
The UX of AI Matters : How does the visual representation of a recommendation...Pierre-Majorique Léger
 
Product thinking and dual track agile
Product thinking and dual track agileProduct thinking and dual track agile
Product thinking and dual track agileAslam Hirani
 
Accessible Information Seeking
Accessible Information SeekingAccessible Information Seeking
Accessible Information Seekingmerriejune
 
Survey knowledge
Survey knowledgeSurvey knowledge
Survey knowledgeTu Tran
 
Intro to Programming (1)
Intro to Programming (1)Intro to Programming (1)
Intro to Programming (1)Justin Reese
 
Game of data: Data driven game design
Game of data: Data driven game designGame of data: Data driven game design
Game of data: Data driven game designMasih Alagheband
 
Marczewski's User Type Workshop #GWC14
Marczewski's User Type Workshop #GWC14Marczewski's User Type Workshop #GWC14
Marczewski's User Type Workshop #GWC14Andrzej Marczewski
 
AYO Social Enterprise x EdgeX Social Ideathon
AYO Social Enterprise x EdgeX Social IdeathonAYO Social Enterprise x EdgeX Social Ideathon
AYO Social Enterprise x EdgeX Social IdeathonJayren Teo 张健荣
 
Election security
Election securityElection security
Election securityDavid Mertz
 
10 NPO Communications and Asking Techniques for Fundraising Success
10 NPO Communications and Asking Techniques for Fundraising Success10 NPO Communications and Asking Techniques for Fundraising Success
10 NPO Communications and Asking Techniques for Fundraising SuccessBloomerang
 
Le Wagon - Product Specs 101
Le Wagon - Product Specs 101Le Wagon - Product Specs 101
Le Wagon - Product Specs 101Boris Paillard
 
Remote, fast, accurate, distributed team decisions
Remote, fast, accurate, distributed team decisionsRemote, fast, accurate, distributed team decisions
Remote, fast, accurate, distributed team decisionsIain Burns
 
A recommendation engine for your applications phpday
A recommendation engine for your applications phpdayA recommendation engine for your applications phpday
A recommendation engine for your applications phpdayMichele Orselli
 

Similaire à Django Multicolumn Joins: Data Locality and Foreign Keys (18)

Surveys That Work: using questionnaires to gather useful data, Seattle 2010
Surveys That Work: using questionnaires to gather useful data, Seattle 2010Surveys That Work: using questionnaires to gather useful data, Seattle 2010
Surveys That Work: using questionnaires to gather useful data, Seattle 2010
 
The UX of AI Matters : How does the visual representation of a recommendation...
The UX of AI Matters : How does the visual representation of a recommendation...The UX of AI Matters : How does the visual representation of a recommendation...
The UX of AI Matters : How does the visual representation of a recommendation...
 
Product thinking and dual track agile
Product thinking and dual track agileProduct thinking and dual track agile
Product thinking and dual track agile
 
Accessible Information Seeking
Accessible Information SeekingAccessible Information Seeking
Accessible Information Seeking
 
Survey knowledge
Survey knowledgeSurvey knowledge
Survey knowledge
 
Amy Jo Kim - MFW15
Amy Jo Kim - MFW15Amy Jo Kim - MFW15
Amy Jo Kim - MFW15
 
Co op talk
Co op talkCo op talk
Co op talk
 
Intro to Programming (1)
Intro to Programming (1)Intro to Programming (1)
Intro to Programming (1)
 
Game of data: Data driven game design
Game of data: Data driven game designGame of data: Data driven game design
Game of data: Data driven game design
 
Marczewski's User Type Workshop #GWC14
Marczewski's User Type Workshop #GWC14Marczewski's User Type Workshop #GWC14
Marczewski's User Type Workshop #GWC14
 
AYO Social Enterprise x EdgeX Social Ideathon
AYO Social Enterprise x EdgeX Social IdeathonAYO Social Enterprise x EdgeX Social Ideathon
AYO Social Enterprise x EdgeX Social Ideathon
 
Election security
Election securityElection security
Election security
 
10 NPO Communications and Asking Techniques for Fundraising Success
10 NPO Communications and Asking Techniques for Fundraising Success10 NPO Communications and Asking Techniques for Fundraising Success
10 NPO Communications and Asking Techniques for Fundraising Success
 
Le Wagon - Product Specs 101
Le Wagon - Product Specs 101Le Wagon - Product Specs 101
Le Wagon - Product Specs 101
 
Remote, fast, accurate, distributed team decisions
Remote, fast, accurate, distributed team decisionsRemote, fast, accurate, distributed team decisions
Remote, fast, accurate, distributed team decisions
 
Gamification course @CafeIT (8-hour)
Gamification course @CafeIT (8-hour)Gamification course @CafeIT (8-hour)
Gamification course @CafeIT (8-hour)
 
A recommendation engine for your applications phpday
A recommendation engine for your applications phpdayA recommendation engine for your applications phpday
A recommendation engine for your applications phpday
 
Game Learning Webinar by Greenbooks & Gamelearn
Game Learning Webinar by Greenbooks & GamelearnGame Learning Webinar by Greenbooks & Gamelearn
Game Learning Webinar by Greenbooks & Gamelearn
 

Plus de Hearsay Systems

"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay Summit
"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay Summit"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay Summit
"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay SummitHearsay Systems
 
"Market Like It's 2017" – Hearsay Summit
"Market Like It's 2017" – Hearsay Summit"Market Like It's 2017" – Hearsay Summit
"Market Like It's 2017" – Hearsay SummitHearsay Systems
 
Selling Insurance: Have You Modernized? [Infographic]
Selling Insurance: Have You Modernized? [Infographic]Selling Insurance: Have You Modernized? [Infographic]
Selling Insurance: Have You Modernized? [Infographic]Hearsay Systems
 
Disruption in Financial Services? A Silicon Valley Perspective
Disruption in Financial Services? A Silicon Valley PerspectiveDisruption in Financial Services? A Silicon Valley Perspective
Disruption in Financial Services? A Silicon Valley PerspectiveHearsay Systems
 
Wealth Management Trends 2016: Findings from Tiburon Advisors
Wealth Management Trends 2016: Findings from Tiburon Advisors Wealth Management Trends 2016: Findings from Tiburon Advisors
Wealth Management Trends 2016: Findings from Tiburon Advisors Hearsay Systems
 
Hearsay Social 2016 Innovation Summit Keynote
Hearsay Social 2016 Innovation Summit KeynoteHearsay Social 2016 Innovation Summit Keynote
Hearsay Social 2016 Innovation Summit KeynoteHearsay Systems
 
2016 Mortgage Banking Executive Summit: The Power of Social Media
2016 Mortgage Banking Executive Summit: The Power of Social Media 2016 Mortgage Banking Executive Summit: The Power of Social Media
2016 Mortgage Banking Executive Summit: The Power of Social Media Hearsay Systems
 
Social Media Compliance: Compliance for the Financial Services Industry in 2016
Social Media Compliance: Compliance for the Financial Services Industry in 2016Social Media Compliance: Compliance for the Financial Services Industry in 2016
Social Media Compliance: Compliance for the Financial Services Industry in 2016Hearsay Systems
 
Local SEO for Financial Advisors
Local SEO for Financial AdvisorsLocal SEO for Financial Advisors
Local SEO for Financial AdvisorsHearsay Systems
 
Social business adoption infographic
Social business adoption infographicSocial business adoption infographic
Social business adoption infographicHearsay Systems
 
Business in the Facebook Era
Business in the Facebook EraBusiness in the Facebook Era
Business in the Facebook EraHearsay Systems
 
4 Timeless Business Lessons Revived in the Social Media Era (Clara Shih, LIM...
4 Timeless Business Lessons Revived in the Social Media Era  (Clara Shih, LIM...4 Timeless Business Lessons Revived in the Social Media Era  (Clara Shih, LIM...
4 Timeless Business Lessons Revived in the Social Media Era (Clara Shih, LIM...Hearsay Systems
 
Hearsay Social's Innovation Summit: Succeeding in the Relationship Era
Hearsay Social's Innovation Summit: Succeeding in the Relationship Era Hearsay Social's Innovation Summit: Succeeding in the Relationship Era
Hearsay Social's Innovation Summit: Succeeding in the Relationship Era Hearsay Systems
 
5 Rules of Sales and Marketing in the Facebook Era
5 Rules of Sales and Marketing in the Facebook Era5 Rules of Sales and Marketing in the Facebook Era
5 Rules of Sales and Marketing in the Facebook EraHearsay Systems
 
Social Selling: How to Use Social Networks to Close More Deals
Social Selling: How to Use Social Networks to Close More DealsSocial Selling: How to Use Social Networks to Close More Deals
Social Selling: How to Use Social Networks to Close More DealsHearsay Systems
 
7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay Social
7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay Social7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay Social
7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay SocialHearsay Systems
 
7 Habits of Highly Successful Social Marketers
7 Habits of Highly Successful Social Marketers7 Habits of Highly Successful Social Marketers
7 Habits of Highly Successful Social MarketersHearsay Systems
 

Plus de Hearsay Systems (17)

"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay Summit
"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay Summit"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay Summit
"The Future of Social: Paid Content, Video, 1:1 Messaging" – Hearsay Summit
 
"Market Like It's 2017" – Hearsay Summit
"Market Like It's 2017" – Hearsay Summit"Market Like It's 2017" – Hearsay Summit
"Market Like It's 2017" – Hearsay Summit
 
Selling Insurance: Have You Modernized? [Infographic]
Selling Insurance: Have You Modernized? [Infographic]Selling Insurance: Have You Modernized? [Infographic]
Selling Insurance: Have You Modernized? [Infographic]
 
Disruption in Financial Services? A Silicon Valley Perspective
Disruption in Financial Services? A Silicon Valley PerspectiveDisruption in Financial Services? A Silicon Valley Perspective
Disruption in Financial Services? A Silicon Valley Perspective
 
Wealth Management Trends 2016: Findings from Tiburon Advisors
Wealth Management Trends 2016: Findings from Tiburon Advisors Wealth Management Trends 2016: Findings from Tiburon Advisors
Wealth Management Trends 2016: Findings from Tiburon Advisors
 
Hearsay Social 2016 Innovation Summit Keynote
Hearsay Social 2016 Innovation Summit KeynoteHearsay Social 2016 Innovation Summit Keynote
Hearsay Social 2016 Innovation Summit Keynote
 
2016 Mortgage Banking Executive Summit: The Power of Social Media
2016 Mortgage Banking Executive Summit: The Power of Social Media 2016 Mortgage Banking Executive Summit: The Power of Social Media
2016 Mortgage Banking Executive Summit: The Power of Social Media
 
Social Media Compliance: Compliance for the Financial Services Industry in 2016
Social Media Compliance: Compliance for the Financial Services Industry in 2016Social Media Compliance: Compliance for the Financial Services Industry in 2016
Social Media Compliance: Compliance for the Financial Services Industry in 2016
 
Local SEO for Financial Advisors
Local SEO for Financial AdvisorsLocal SEO for Financial Advisors
Local SEO for Financial Advisors
 
Social business adoption infographic
Social business adoption infographicSocial business adoption infographic
Social business adoption infographic
 
Business in the Facebook Era
Business in the Facebook EraBusiness in the Facebook Era
Business in the Facebook Era
 
4 Timeless Business Lessons Revived in the Social Media Era (Clara Shih, LIM...
4 Timeless Business Lessons Revived in the Social Media Era  (Clara Shih, LIM...4 Timeless Business Lessons Revived in the Social Media Era  (Clara Shih, LIM...
4 Timeless Business Lessons Revived in the Social Media Era (Clara Shih, LIM...
 
Hearsay Social's Innovation Summit: Succeeding in the Relationship Era
Hearsay Social's Innovation Summit: Succeeding in the Relationship Era Hearsay Social's Innovation Summit: Succeeding in the Relationship Era
Hearsay Social's Innovation Summit: Succeeding in the Relationship Era
 
5 Rules of Sales and Marketing in the Facebook Era
5 Rules of Sales and Marketing in the Facebook Era5 Rules of Sales and Marketing in the Facebook Era
5 Rules of Sales and Marketing in the Facebook Era
 
Social Selling: How to Use Social Networks to Close More Deals
Social Selling: How to Use Social Networks to Close More DealsSocial Selling: How to Use Social Networks to Close More Deals
Social Selling: How to Use Social Networks to Close More Deals
 
7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay Social
7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay Social7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay Social
7 Habits of Highly Successful Social Marketers, Clara Shih, CEO, Hearsay Social
 
7 Habits of Highly Successful Social Marketers
7 Habits of Highly Successful Social Marketers7 Habits of Highly Successful Social Marketers
7 Habits of Highly Successful Social Marketers
 

Dernier

Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMVoces Mineras
 
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxThe-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxmbikashkanyari
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfRbc Rbcua
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdfKhaled Al Awadi
 
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxFinancial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxsaniyaimamuddin
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCRashishs7044
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Doge Mining Website
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?Olivia Kresic
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03DallasHaselhorst
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFChandresh Chudasama
 
Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchirictsugar
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCRashishs7044
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
Kenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith PereraKenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith Pereraictsugar
 

Dernier (20)

Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQM
 
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCREnjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
 
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxThe-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdf
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
 
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxFinancial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDF
 
Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchir
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
Kenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith PereraKenya Coconut Production Presentation by Dr. Lalith Perera
Kenya Coconut Production Presentation by Dr. Lalith Perera
 

Django Multicolumn Joins: Data Locality and Foreign Keys

  • 1. Django Meetup: Django Multicolumn Joins Jeremy Tillman Software Engineer, Hearsay Social @hssengineering
  • 2. Django Multicolumn Joins | © 2012 Hearsay Social 2 About Me • Joined Hearsay Social May 2012 as Software Engineering Generalist • Computer Engineer BA, Purdue University • 3 years @ Microsoft working on versions of Window Server • 9 years of databases experience – Access, SQL Server, MySql • Loves Sea Turtles!
  • 3. Django Multicolumn Joins | © 2012 Hearsay Social 3 Why do we want multicolumn joins?
  • 4. Django Multicolumn Joins | © 2012 Hearsay Social 4 Django First App: Poll example class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
  • 5. Django Multicolumn Joins | © 2012 Hearsay Social 5 What if we stored Polls for X number of customers? class Customer(models.Model): name = models.CharField(max_length=100) class Meta: ordering = („name‟,) class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) class Poll(models.Model): customer = models.ForeignKey(Customer) question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') CREATE TABLE customer( id INT NOT NULL AUTO_INCRMENT PRIMARY KEY, name VARCHAR(100) NOT NULL); CREATE TABLE poll( id INT NOT NULL AUTO_INCRMENT PRIMARY KEY, customer_id INT NOT NULL, question VARCHAR(200) NOT NULL, pub_date DATETIME NOT NULL, INDEX idx_customer (customer_id)); CREATE TABLE choice( id INT NOT NULL AUTO_INCRMENT PRIMARY KEY, poll INT NOT NULL, choice_text VARCHAR (200), votes INT NOT NULL DEFAULT 0, INDEX idx_poll (poll_id));
  • 6. Django Multicolumn Joins | © 2012 Hearsay Social 6 How is our data being stored? CREATE TABLE choice( id INT NOT NULL AUTO_INCRMENT PRIMARY KEY, poll_id INT NOT NULL, choice_text VARCHAR (200), votes INT NOT NULL DEFAULT 0, INDEX idx_poll (poll_id)); id poll_id choice_text votes 1 1 Ham 5 2 7 Aries 8 3 2 Elephant 9 …. … … … 23,564,149 1 All of the above 2 23,564,150 74 Sea turtle 7
  • 7. Django Multicolumn Joins | © 2012 Hearsay Social 7 Data locality part 1: Scope by poll CREATE TABLE choice( id INT NOT NULL, poll_id INT NOT NULL, choice_text VARCHAR (200), votes INT NOT NULL DEFAULT 0, PRIMARY KEY (poll_id, id)); id poll_id choice_text votes 1 1 Ham 5 1,562 1 Turkey 46 23,564,149 1 All of the above 2 …. … … … 18,242,234 74 Jelly fish 0 23,564,150 74 Sea turtle 7
  • 8. Django Multicolumn Joins | © 2012 Hearsay Social 8 Data locality part 2: Scope by customer CREATE TABLE choice( id INT NOT NULL, customer_id INT NOT NULL, poll_id INT NOT NULL, choice_text VARCHAR (200), votes INT NOT NULL DEFAULT 0, PRIMARY KEY (customer_id, poll_id, id)); id poll_id customer_id choice_text votes 1 1 1 Ham 5 1,562 1 1 Turkey 46 23,564,149 1 1 All of the above 2 18,242,234 74 1 Jelly fish 0 23,564,150 74 1 Sea turtle 7 … … … … …
  • 9. Django Multicolumn Joins | © 2012 Hearsay Social 9 Representation in Django Models class Customer(models.Model): name = models.CharField(max_length=100) class Meta: ordering = („name‟,) class Choice(models.Model): customer = models.ForeignKey(Customer) poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) class Poll(models.Model): customer = models.ForeignKey(Customer) question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
  • 10. Django Multicolumn Joins | © 2012 Hearsay Social 10 Customer Load/Data Balance customer_id id 1 1 2 2 3 3 4 4
  • 11. Django Multicolumn Joins | © 2012 Hearsay Social 11 Customer Load/Data Balance: Split Customers customer_id id 3 3 3 5 4 4 4 6 customer_id id 1 1 1 5 2 2 2 6
  • 12. Django Multicolumn Joins | © 2012 Hearsay Social 12 Add DB and Balance Load: id collision customer_id id 3 3 3 5 customer_id id 1 1 1 5 customer_id id 2 2 2 6 4 4 4 6
  • 13. Django Multicolumn Joins | © 2012 Hearsay Social 13 Queries: Find all choices for a poll? customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 14. Django Multicolumn Joins | © 2012 Hearsay Social 14 Queries: Find all choices for a poll? Attempt 1) Using related set target_poll.choice_set.all() or Choice.objects.filter(poll=target_poll) SELECT * FROM choice WHERE poll_id = 1 customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 15. Django Multicolumn Joins | © 2012 Hearsay Social 15 Queries: Find all choices for a poll? Attempt 2) Adding a F expression target_poll.choice_set.all(customer=F(„poll__customer‟)) or Choice.objects.filter(poll=target_poll, customer=F(„poll__customer‟)) SELECT c.* FROM choice c INNER JOIN poll p ON c.poll_id = p.id WHERE c.poll_id = 1 AND c.customer_id = p.customer_id; customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 16. Django Multicolumn Joins | © 2012 Hearsay Social 16 Queries: Find all choices for a poll? Attempt 3) Filter explicitly target_poll.choice_set.all(customer=target_poll.customer) or Choice.objects.filter(poll=target_poll, customer=target_poll.customer) SELECT * FROM choice WHERE poll_id = 1 AND customer_id = 2; customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 17. Django Multicolumn Joins | © 2012 Hearsay Social 17 Field Assignment quantity_inn = Customer.objects.create(id=15, name=„Quantity Inn‟) quantity_poll = Poll.objects.create(id=1, company=quantity_inn, question=„What size bed do you prefer?‟) choice1 = Choice(id=1, choice_text=“King”, poll=quantity_poll) choice1.customer_id ??????   choice1.customer = quantity_poll.customer Repetitive
  • 18. Django Multicolumn Joins | © 2012 Hearsay Social 18 What do we do?
  • 19. Django Multicolumn Joins | © 2012 Hearsay Social 19 Solution via Django 1.6 class ForeignObject(othermodel, from_fields, to_fields[, **options]) where: from django.db.models import ForeignObject
  • 20. Django Multicolumn Joins | © 2012 Hearsay Social 20 ForeignObject Usage class ForeignModel(models.Model): id1 = models.IntegerField() id2 = models.IntegerField() class ReferencingModel(models.Model): om_id1 = models.IntegerField() om_id2 = models.IntegerField() om = ForeignObject(ForeignModel, from_fields=(om_id1, om_id2), to_fields=(id1, id2))
  • 21. Django Multicolumn Joins | © 2012 Hearsay Social 21 Conversion from ForeignKey to ForeignObject class Choice(models.Model): customer = models.ForeignKey(Customer) poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) class Choice(models.Model): customer = models.ForeignKey(Customer) poll_id = models.IntegerField() choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) poll = models.ForeignObject(Poll, from_fields=(‘customer’, ‘poll_id’), to_fields=(‘customer’, ‘id’))
  • 22. Django Multicolumn Joins | © 2012 Hearsay Social 22 Queries with ForeignObject Attempt 1) Using related set target_poll.choice_set.all() SELECT * FROM choice WHERE poll_id = 1 AND customer_id = 2; customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 23. Django Multicolumn Joins | © 2012 Hearsay Social 23 Queries with ForeignObject Attempt 2) Manually stated Choice.objects.filter(poll=target_poll) SELECT * FROM choice WHERE poll_id = 1 AND customer_id = 2; customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 24. Django Multicolumn Joins | © 2012 Hearsay Social 24 Queries with ForeignObject Attempt 2) Manually stated w/tuple Choice.objects.filter(poll=(2, 1)) SELECT * FROM choice WHERE poll_id = 1 AND customer_id = 2; customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 25. Django Multicolumn Joins | © 2012 Hearsay Social 25 Field Assignment with ForeignObject quantity_inn = Customer.objects.create(id=15, name=„Quantity Inn‟) quantity_poll = Poll.objects.create(id=1, company=quantity_inn, question=„What size bed do you prefer?‟) choice1 = Choice(id=1, choice_text=“King”, poll=quantity_poll) choice1.customer_id >> 15   choice1.customer = quantity_poll.customer  Not needed
  • 26. Django Multicolumn Joins | © 2012 Hearsay Social 26 “With great power comes great responsibility”
  • 27. Django Multicolumn Joins | © 2012 Hearsay Social 27 Tuple ordering matters Choice.objects.filter(poll=(1, 2)) SELECT * FROM choice WHERE poll_id = 2 AND customer_id = 1; poll = models.ForeignObject(Poll, from_fields=(‘customer’, ‘poll_id’), to_fields=(‘customer’, ‘id’)) customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 28. Django Multicolumn Joins | © 2012 Hearsay Social 28 IN Operator Choice.objects.filter(poll__in=[(2, 1), (2, 2)]) SELECT * FROM choice WHERE (poll_id = 1 AND customer_id = 2) OR (poll_id = 2 AND customer_id = 2); poll = models.ForeignObject(Poll, from_fields=(‘customer’, ‘poll_id’), to_fields=(‘customer’, ‘id’)) customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 29. Django Multicolumn Joins | © 2012 Hearsay Social 29 IN Operator w/queryset Choice.objects.filter(poll__in= Poll.objects.filter(customer_id=2)) SELECT c.* FROM choice c WHERE EXISTS (SELECT p.customer_id, p.id FROM poll p WHERE p.customer_id = 2 AND p.customer_id = c.customer_id AND p.id = c.poll_id); poll = models.ForeignObject(Poll, from_fields=(‘customer’, ‘poll_id’), to_fields=(‘customer’, ‘id’)) customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 30. Django Multicolumn Joins | © 2012 Hearsay Social 30 IN Operator with MySql Choice.objects.filter(poll__in=[(2, 1), (2, 2)]) SELECT * FROM choice WHERE (poll_id, customer_id) IN ((1, 2), (2, 2)); poll = models.ForeignObject(Poll, from_fields=(‘customer’, ‘poll_id’), to_fields=(‘customer’, ‘id’)) customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 31. Django Multicolumn Joins | © 2012 Hearsay Social 31 IN Operator w/queryset & MySQL Choice.objects.filter(poll__in= Poll.objects.filter(customer_id=2)) SELECT c.* FROM choice c WHERE (c.customer_id, c.poll_id) IN (SELECT p.customer_id, p.id FROM poll p WHERE p.customer_id = 2); poll = models.ForeignObject(Poll, from_fields=(‘customer’, ‘poll_id’), to_fields=(‘customer’, ‘id’)) customer_id id question 1 1 What’s your seat pref.? 1 2 Are you married? 2 1 Gender? 2 2 Did you have fun? customer_id poll_id id choice_text 1 1 1 Window 1 1 2 Ailse 1 2 1 Yes 1 2 2 No 2 1 1 Male 2 1 2 Female 2 2 1 Yes? Poll Choice
  • 32. Django Multicolumn Joins | © 2012 Hearsay Social 32 ForeignKey vs ForeignObject Whats the difference? ForeignKey is a ForeignObject pseudo def: ForeignObject(OtherModel, from_fields=((„self‟,)), to_fields=((OtherModel._meta.pk.name),))
  • 33. Django Multicolumn Joins | © 2012 Hearsay Social 33 ForeignKey usage: Order By Example Poll.objects.order_by(„customer‟) class Customer(models.Model): name = models.CharField(max_length=100) class Meta: ordering = („name‟,) class Poll(models.Model): customer = models.ForeignKey(Customer) question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
  • 34. Django Multicolumn Joins | © 2012 Hearsay Social 34 ForeignKey usage: Order By Example Poll.objects.order_by(„customer‟) SELECT p.* from poll INNER JOIN customer c ON p.customer_id = c.id ORDER BY c.name ASC; class Customer(models.Model): name = models.CharField(max_length=100) class Meta: ordering = („name‟,) class Poll(models.Model): customer = models.ForeignKey(Customer) question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
  • 35. Django Multicolumn Joins | © 2012 Hearsay Social 35 ForeignKey usage: Order By Example Poll.objects.order_by(„customer_id‟) SELECT p.* from poll INNER JOIN customer c ON p.customer_id = c.id ORDER BY c.name ASC; class Customer(models.Model): name = models.CharField(max_length=100) class Meta: ordering = („name‟,) class Poll(models.Model): customer = models.ForeignKey(Customer) question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') Alias for customer
  • 36. Django Multicolumn Joins | © 2012 Hearsay Social 36 ForeignKey usage: Order By Example Poll.objects.order_by(„customer__id‟) SELECT p.* from poll INNER JOIN customer c ON p.customer_id = c.id ORDER BY p.customer_id ASC; class Customer(models.Model): name = models.CharField(max_length=100) class Meta: ordering = („name‟,) class Poll(models.Model): customer = models.ForeignKey(Customer) question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published')
  • 37. Django Multicolumn Joins | © 2012 Hearsay Social 37 ForeignKey usage: Order By Example Poll.objects.order_by(„customer_id‟) SELECT * from poll ORDER BY customer_id ASC; class Customer(models.Model): name = models.CharField(max_length=100) class Meta: ordering = („name‟,) class Poll(models.Model): customer_id = models.IntegerField() question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') customer = models.ForeignObject(Customer, from_fields=(„customer_id‟,), to_fields=(„id‟,))
  • 38. Django Multicolumn Joins | © 2012 Hearsay Social 38 Still more fun stuff • ForeignObject.get_extra_description_filter • ForeignObject.get_extra_restriction • More to come
  • 39. Django Multicolumn Joins | © 2012 Hearsay Social 39 Dig for more information: • ForeignObject source • django/db/models/fields/related.py • V1 Version of Patch (Based of Django 1.4) • https://github.com/jtillman/django/tree/MultiColumnJoin • Blog post to come • Hearsay Social Blog (http://engineering.hearsaysocial.com/)
  • 40. Django Multicolumn Joins | © 2012 Hearsay Social 40 Questions?