ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
Django Tips and Tricks@andymccurdyhttp://github.com/andymccurdy/django-tips-and-tricks
Something Went Wrong
Debugging Production# site.wsgifrom whiskey.core import StaffDebugWSGIHandlerapplication = handlers.StaffDebugWSGIHandler()
Something Useful
Foreign Key Woesclass Profile(models.Model):    name = models.CharField(max_length=64)class Image(models.Model):    profile = models.ForeignKey(Profile)>>> p = Profile.objects.create(name='andy')>>> i = Image.objects.create(profile=p)>>> p.delete()>>> Image.objects.filter(profile=p)[]
Foreign Key Woesclass Profile(models.Model):    name = models.CharField(max_length=64)    icon = models.ForeignKey(Image, null=True)class Image(models.Model):    pass>>> i = Image.objects.create()>>> p = Profile.objects.create(name='andy', icon=i)>>> i.delete()>>> Profile.objects.filter(name='andy')[] # WTF ?!?!?!?!?!?
Django tips and_tricks (1)
Main Ticket: #7539First Reported: 6/25/2008 !!!Duplicate Tickets:    #10262, #6870, #12382, #12166
NullableForeignKeyfrom whiskey.core import NullableForeignKeyclass Profile(models.Model):    name = models.CharField(max_length=64)    icon = NullableForeignKey(Image)class Image(models.Model):    pass>>> i = Image.objects.create()>>> p = Profile.objects.create(name='andy', icon=i)>>> i.delete()>>> Profile.objects.filter(name='andy')>>> [<Profile: Profile object>]>>> print Profile.objects.filter(name='andy')[0].iconNone
Concurrency Issuesdef like(request, pk):    m = MyObject.objects.get(pk=pk)    m.likes += 1    m.save()    return HttpResponse('')What happens if two requests come in at the same time?
Django "F" ExpressionsNew in Django 1.1from django.db.models import Fdef like(request, pk):    m = MyObject.objects.get(pk=pk)    m.likes = F('likes') + 1    m.save()    return HttpResponse('')
.save() Updates All Fieldsfrom django.db.models import Fdef like(request, pk):    m = MyObject.objects.get(pk=pk)    m.likes = F('likes') + 1    m.save() # race condition with "hates"    return HttpResponse('')def hate(request, pk):    m = MyObject.objects.get(pk=pk)    m.hates = F('hates') + 1    m.save() # race condition with "likes"    return HttpResponse('')
QuerySet.update()from django.db.models import Fdef like(request, pk):MyObject.objects.filter(pk=pk).update(        likes=F('likes') + 1)   return HttpResponse('')def hate(request, pk):MyObject.objects.filter(pk=pk).update(        likes=F('hates') + 1)    return HttpResponse('')That's a lot of typing.What about ORM cache invalidation?
Even Easierfrom whiskey.core import updatedef like(request, pk):    m = MyObject.objects.get(pk=pk)update(m, likes=F('likes') + 1)    return HttpResponse('')def hate(request, pk):    m = MyObject.objects.get(pk=pk)update(m, hates=F('hates') + 1)    return HttpResponse('')
Thanks!Questions?http://github.com/andymccurdy/django-tips-and-tricks@andymccurdyandy@whiskeymedia.comWe're Hiring!

More Related Content

What's hot (10)

HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
bbeeley
?
Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018
Joke Puts
?
Flutter 4
Flutter 4Flutter 4
Flutter 4
Warren Lin
?
Espresso devoxx 2014
Espresso devoxx 2014Espresso devoxx 2014
Espresso devoxx 2014
Publicis Sapient Engineering
?
Contraints
ContraintsContraints
Contraints
Anar Godjaev
?
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf
Rafael Dohms
?
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
David Golden
?
Fluentlenium
FluentleniumFluentlenium
Fluentlenium
MathildeLemee
?
Java interface and inheritance
Java interface and inheritanceJava interface and inheritance
Java interface and inheritance
JaromirJagr
?
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...
Rafael Dohms
?
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
bbeeley
?
Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018Manipulating Magento - Meet Magento Netherlands 2018
Manipulating Magento - Meet Magento Netherlands 2018
Joke Puts
?
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHPKonf
Rafael Dohms
?
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
David Golden
?
Java interface and inheritance
Java interface and inheritanceJava interface and inheritance
Java interface and inheritance
JaromirJagr
?
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...
¡°Writing code that lasts¡± ¡­ or writing code you won¡¯t hate tomorrow. - PHP Yo...
Rafael Dohms
?

Similar to Django tips and_tricks (1) (20)

Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
Eric Satterwhite
?
Django Search
Django SearchDjango Search
Django Search
Peter Herndon
?
PyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven DevelopmentPyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven Development
Tudor Munteanu
?
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
Python Ireland
?
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
Shawn Rider
?
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
Simon Willison
?
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
Leonardo Soto
?
PyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appenginePyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appengine
Pranav Prakash
?
Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6
Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6
Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6
Technopark
?
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
Mike Dirolf
?
Practical Celery
Practical CeleryPractical Celery
Practical Celery
Cameron Maske
?
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Mir Nazim
?
Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6
Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6
Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6
Technopark
?
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
J?rn Zaefferer
?
Django
DjangoDjango
Django
webuploader
?
§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django
§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django
§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django
MoscowDjango
?
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
Tom¨¢s Henr¨ªquez
?
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
?
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
Jeffrey Zinn
?
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
Leonardo Soto
?
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
Eric Satterwhite
?
PyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven DevelopmentPyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven Development
Tudor Munteanu
?
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
Python Ireland
?
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
Shawn Rider
?
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
Leonardo Soto
?
PyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appenginePyCon India 2010 Building Scalable apps using appengine
PyCon India 2010 Building Scalable apps using appengine
Pranav Prakash
?
Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6
Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6
Web §à§ã§Ö§ß§î 2012 §Ý§Ö§Ü§è§Ú§ñ 6
Technopark
?
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
Mike Dirolf
?
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Mir Nazim
?
Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6
Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6
Web §Ó§Ö§ã§ß§Ñ 2013 §Ý§Ö§Ü§è§Ú§ñ 6
Technopark
?
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
J?rn Zaefferer
?
§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django
§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django
§´§Ö§ã§ä§Ú§â§à§Ó§Ñ§ß§Ú§Ö §Ú Django
MoscowDjango
?
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
Leonardo Soto
?

Recently uploaded (20)

EaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial KeyEaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial Key
kherorpacca127
?
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
maharajput103
?
Endpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore ItEndpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore It
MSP360
?
How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...
How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...
How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...
ScyllaDB
?
Deno ...................................
Deno ...................................Deno ...................................
Deno ...................................
Robert MacLean
?
BoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is DynamicBoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is Dynamic
Ortus Solutions, Corp
?
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-StoryRevolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
ssuser52ad5e
?
Transform Your Future with Front-End Development Training
Transform Your Future with Front-End Development TrainingTransform Your Future with Front-End Development Training
Transform Your Future with Front-End Development Training
Vtechlabs
?
UiPath Automation Developer Associate Training Series 2025 - Session 2
UiPath Automation Developer Associate Training Series 2025 - Session 2UiPath Automation Developer Associate Training Series 2025 - Session 2
UiPath Automation Developer Associate Training Series 2025 - Session 2
DianaGray10
?
Unlock AI Creativity: Image Generation with DALL¡¤E
Unlock AI Creativity: Image Generation with DALL¡¤EUnlock AI Creativity: Image Generation with DALL¡¤E
Unlock AI Creativity: Image Generation with DALL¡¤E
Expeed Software
?
A Framework for Model-Driven Digital Twin Engineering
A Framework for Model-Driven Digital Twin EngineeringA Framework for Model-Driven Digital Twin Engineering
A Framework for Model-Driven Digital Twin Engineering
Daniel Lehner
?
Q4 2024 Earnings and Investor Presentation
Q4 2024 Earnings and Investor PresentationQ4 2024 Earnings and Investor Presentation
Q4 2024 Earnings and Investor Presentation
Dropbox
?
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar PatturajInside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
ScyllaDB
?
Gojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptxGojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptx
V3cube
?
Field Device Management Market Report 2030 - TechSci Research
Field Device Management Market Report 2030 - TechSci ResearchField Device Management Market Report 2030 - TechSci Research
Field Device Management Market Report 2030 - TechSci Research
Vipin Mishra
?
30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...
30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...
30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...
ScyllaDB
?
Backstage Software Templates for Java Developers
Backstage Software Templates for Java DevelopersBackstage Software Templates for Java Developers
Backstage Software Templates for Java Developers
Markus Eisele
?
Fl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free DownloadFl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free Download
kherorpacca127
?
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial PresentationMIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND CTI
?
The Future of Repair: Transparent and Incremental by Botond De?nes
The Future of Repair: Transparent and Incremental by Botond De?nesThe Future of Repair: Transparent and Incremental by Botond De?nes
The Future of Repair: Transparent and Incremental by Botond De?nes
ScyllaDB
?
EaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial KeyEaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial Key
kherorpacca127
?
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
maharajput103
?
Endpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore ItEndpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore It
MSP360
?
How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...
How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...
How Discord Indexes Trillions of Messages: Scaling Search Infrastructure by V...
ScyllaDB
?
Deno ...................................
Deno ...................................Deno ...................................
Deno ...................................
Robert MacLean
?
BoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is DynamicBoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is Dynamic
Ortus Solutions, Corp
?
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-StoryRevolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
ssuser52ad5e
?
Transform Your Future with Front-End Development Training
Transform Your Future with Front-End Development TrainingTransform Your Future with Front-End Development Training
Transform Your Future with Front-End Development Training
Vtechlabs
?
UiPath Automation Developer Associate Training Series 2025 - Session 2
UiPath Automation Developer Associate Training Series 2025 - Session 2UiPath Automation Developer Associate Training Series 2025 - Session 2
UiPath Automation Developer Associate Training Series 2025 - Session 2
DianaGray10
?
Unlock AI Creativity: Image Generation with DALL¡¤E
Unlock AI Creativity: Image Generation with DALL¡¤EUnlock AI Creativity: Image Generation with DALL¡¤E
Unlock AI Creativity: Image Generation with DALL¡¤E
Expeed Software
?
A Framework for Model-Driven Digital Twin Engineering
A Framework for Model-Driven Digital Twin EngineeringA Framework for Model-Driven Digital Twin Engineering
A Framework for Model-Driven Digital Twin Engineering
Daniel Lehner
?
Q4 2024 Earnings and Investor Presentation
Q4 2024 Earnings and Investor PresentationQ4 2024 Earnings and Investor Presentation
Q4 2024 Earnings and Investor Presentation
Dropbox
?
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar PatturajInside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
ScyllaDB
?
Gojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptxGojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptx
V3cube
?
Field Device Management Market Report 2030 - TechSci Research
Field Device Management Market Report 2030 - TechSci ResearchField Device Management Market Report 2030 - TechSci Research
Field Device Management Market Report 2030 - TechSci Research
Vipin Mishra
?
30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...
30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...
30B Images and Counting: Scaling Canva's Content-Understanding Pipelines by K...
ScyllaDB
?
Backstage Software Templates for Java Developers
Backstage Software Templates for Java DevelopersBackstage Software Templates for Java Developers
Backstage Software Templates for Java Developers
Markus Eisele
?
Fl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free DownloadFl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free Download
kherorpacca127
?
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial PresentationMIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND CTI
?
The Future of Repair: Transparent and Incremental by Botond De?nes
The Future of Repair: Transparent and Incremental by Botond De?nesThe Future of Repair: Transparent and Incremental by Botond De?nes
The Future of Repair: Transparent and Incremental by Botond De?nes
ScyllaDB
?

Django tips and_tricks (1)

  • 1. Django Tips and Tricks@andymccurdyhttp://github.com/andymccurdy/django-tips-and-tricks
  • 3. Debugging Production# site.wsgifrom whiskey.core import StaffDebugWSGIHandlerapplication = handlers.StaffDebugWSGIHandler()
  • 5. Foreign Key Woesclass Profile(models.Model): name = models.CharField(max_length=64)class Image(models.Model): profile = models.ForeignKey(Profile)>>> p = Profile.objects.create(name='andy')>>> i = Image.objects.create(profile=p)>>> p.delete()>>> Image.objects.filter(profile=p)[]
  • 6. Foreign Key Woesclass Profile(models.Model): name = models.CharField(max_length=64) icon = models.ForeignKey(Image, null=True)class Image(models.Model): pass>>> i = Image.objects.create()>>> p = Profile.objects.create(name='andy', icon=i)>>> i.delete()>>> Profile.objects.filter(name='andy')[] # WTF ?!?!?!?!?!?
  • 8. Main Ticket: #7539First Reported: 6/25/2008 !!!Duplicate Tickets: #10262, #6870, #12382, #12166
  • 9. NullableForeignKeyfrom whiskey.core import NullableForeignKeyclass Profile(models.Model): name = models.CharField(max_length=64) icon = NullableForeignKey(Image)class Image(models.Model): pass>>> i = Image.objects.create()>>> p = Profile.objects.create(name='andy', icon=i)>>> i.delete()>>> Profile.objects.filter(name='andy')>>> [<Profile: Profile object>]>>> print Profile.objects.filter(name='andy')[0].iconNone
  • 10. Concurrency Issuesdef like(request, pk): m = MyObject.objects.get(pk=pk) m.likes += 1 m.save() return HttpResponse('')What happens if two requests come in at the same time?
  • 11. Django "F" ExpressionsNew in Django 1.1from django.db.models import Fdef like(request, pk): m = MyObject.objects.get(pk=pk) m.likes = F('likes') + 1 m.save() return HttpResponse('')
  • 12. .save() Updates All Fieldsfrom django.db.models import Fdef like(request, pk): m = MyObject.objects.get(pk=pk) m.likes = F('likes') + 1 m.save() # race condition with "hates" return HttpResponse('')def hate(request, pk): m = MyObject.objects.get(pk=pk) m.hates = F('hates') + 1 m.save() # race condition with "likes" return HttpResponse('')
  • 13. QuerySet.update()from django.db.models import Fdef like(request, pk):MyObject.objects.filter(pk=pk).update( likes=F('likes') + 1) return HttpResponse('')def hate(request, pk):MyObject.objects.filter(pk=pk).update( likes=F('hates') + 1) return HttpResponse('')That's a lot of typing.What about ORM cache invalidation?
  • 14. Even Easierfrom whiskey.core import updatedef like(request, pk): m = MyObject.objects.get(pk=pk)update(m, likes=F('likes') + 1) return HttpResponse('')def hate(request, pk): m = MyObject.objects.get(pk=pk)update(m, hates=F('hates') + 1) return HttpResponse('')