SlideShare uma empresa Scribd logo
1 de 10
Django:
Legacy DB
Integrations
How it is possible to integrate a django project
with a legacy database system
• Django is best suited for developing new applications.
• In case you want to use it in an already existing ecosystem you have to bear
in mind:
• To use all the built-in applications you need to create some tables.
• You can use many databases, one for the legacy data and one for the
django’s functionalities
• If your database is not well designed probably you’ll lost some of the
django’s orm features.
• Better if your legacy database is read-only
Assumptions
• Standard way:
• Let django creates users, group and permission tables in a database for you.
• All the built-ins work well.
• Custom way:
• Use your authentication system writing a custom authentication’s backend and plug
it in django
• Write a custom user model based on your legacy table and substitute the django
user model with it.
• You have to implements some methods in order to maintain compatibility with the
django’s built-ins
• Example: http://tomforb.es/using-a-custom-sqlalchemy-users-model-with-django
Django
authentication system
• Configure the database parameters into the settings.py
• Do one or more of the followings:
• Run inspectdb over your schema
• Manually create models from tables
• Manually create unmanaged models from database views
• Manually create unmanaged models from RawQuerySet
• Use Python DB API or another ORM
Integrate django with your legacy db
• Django tries to write all models for you by reverse engineering your database.
• By default all the generated models are unmanaged (you can’t apply
migrations)
• Inspectdb is meant as a shortcut, not as definitive model generation. Indeed
you’ll have to look over the generated models yourself to make customizations:
• Make sure that all models have a primary key
• Rearrange models’ order
• Rename models’ fields with more meaningful names
Inspectdb command
python manage.py inspectdb > models.py
• Naming:
• You can call your model and its fields as you like.
• You can specify the table name inside model’s Meta class
• You can specifythe column’ s names using the field’attribute column_name
• Foreign Keys:
• You can specify all the foreign keys you tables has.
• You can also specify foreign keys if there aren’t real constraint into the table
• It is sufficient that the column used as foreign key contains the related table’s ids.
• You don’t have to specify all columns as fields, just the one you will use
• You have to specify the primary key field
Manually create models from tables
• You can create your models starting from a logical or materialized view in
the same way you do for the tables.
• You have to specify the primary key field
• Same Naming and Foreign keys rules
• You cannot use these models to insert, delete or update
• They must be unmanaged
• You need databases authorizations in order to create custom views
Manually create models from views
• The model need to have a custom Manager (the one who retrieves the data and
instantiates the model)
• The custom manager use a RawQuerySet object to query the db.
• The query must retrieve all the columns specified in the model
• The query can span across multiple tables
• You have to specify the primary key field
• Same Naming and Foreign keys rules
• You can’t use Django ORM features, you have to implements all the query methods you
need
• RawQuerySet allows you to make parameterized queries
Manually create models from
RawQuerySet
• Django provide a way to perform query directly to the db via django.db.connection:
https://docs.djangoproject.com/en/1.7/topics/db/sql/#executing-custom-sql-directly
• You can execute either SELECT, INSERT, DELETE or UPDATE but you can’t use django’s
models.
• Alternatively you can use a completely different ORM like SQLAlchemy to manage your
database.
• Both these methods cannot be compatible with many of the built-in features of django.
Use Python DB API or other ORM
Constraints Model
instances
ORM query
and filtering
on the same
model
ORM
relationship
queries
ORM Insert,
Update and
Delete
Operations
Django Admin Django
Migrate
Inspectdb • Every model must have only
one field with PrimaryKey =
True
• Inspectdb runs across all
tables in the schema
• Manually check the models
compliance
YES YES YES If the
related models
are ORM query
compliance
YES YES YES if
managed =
True
Manually
created
models from
tables
• Every model must have only
one field with PrimaryKey =
True
• You have to create a model
for each needed table
YES YES YES If the
related models
are ORM query
compliance
YES YES YES if
managed =
True
Manually
created
unmanaged
models from
views
• Every model must have only
one field with PrimaryKey =
True (easly done inside sql
with row_count)
• Database write permission
needed
YES YES YES If the
related models
are ORM query
compliance
NO YES but read
only
NO
RawQuerySet • Every model must have only
one field with PrimaryKey =
True (easly done inside sql
with row_count)
• You have to write raw sql
inside python’s scripts
YES NO, you
have to
write every
query
method by
yourself
YES If the
related models
are ORM query
compliance
NO NO NO
Python DB
API or other
ORMs
• You have to do all by hand!!! NO NO NO NO NO NO
Database integrations summary

Mais conteúdo relacionado

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Destaque

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Destaque (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

Django legacy database integrations

  • 1. Django: Legacy DB Integrations How it is possible to integrate a django project with a legacy database system
  • 2. • Django is best suited for developing new applications. • In case you want to use it in an already existing ecosystem you have to bear in mind: • To use all the built-in applications you need to create some tables. • You can use many databases, one for the legacy data and one for the django’s functionalities • If your database is not well designed probably you’ll lost some of the django’s orm features. • Better if your legacy database is read-only Assumptions
  • 3. • Standard way: • Let django creates users, group and permission tables in a database for you. • All the built-ins work well. • Custom way: • Use your authentication system writing a custom authentication’s backend and plug it in django • Write a custom user model based on your legacy table and substitute the django user model with it. • You have to implements some methods in order to maintain compatibility with the django’s built-ins • Example: http://tomforb.es/using-a-custom-sqlalchemy-users-model-with-django Django authentication system
  • 4. • Configure the database parameters into the settings.py • Do one or more of the followings: • Run inspectdb over your schema • Manually create models from tables • Manually create unmanaged models from database views • Manually create unmanaged models from RawQuerySet • Use Python DB API or another ORM Integrate django with your legacy db
  • 5. • Django tries to write all models for you by reverse engineering your database. • By default all the generated models are unmanaged (you can’t apply migrations) • Inspectdb is meant as a shortcut, not as definitive model generation. Indeed you’ll have to look over the generated models yourself to make customizations: • Make sure that all models have a primary key • Rearrange models’ order • Rename models’ fields with more meaningful names Inspectdb command python manage.py inspectdb > models.py
  • 6. • Naming: • You can call your model and its fields as you like. • You can specify the table name inside model’s Meta class • You can specifythe column’ s names using the field’attribute column_name • Foreign Keys: • You can specify all the foreign keys you tables has. • You can also specify foreign keys if there aren’t real constraint into the table • It is sufficient that the column used as foreign key contains the related table’s ids. • You don’t have to specify all columns as fields, just the one you will use • You have to specify the primary key field Manually create models from tables
  • 7. • You can create your models starting from a logical or materialized view in the same way you do for the tables. • You have to specify the primary key field • Same Naming and Foreign keys rules • You cannot use these models to insert, delete or update • They must be unmanaged • You need databases authorizations in order to create custom views Manually create models from views
  • 8. • The model need to have a custom Manager (the one who retrieves the data and instantiates the model) • The custom manager use a RawQuerySet object to query the db. • The query must retrieve all the columns specified in the model • The query can span across multiple tables • You have to specify the primary key field • Same Naming and Foreign keys rules • You can’t use Django ORM features, you have to implements all the query methods you need • RawQuerySet allows you to make parameterized queries Manually create models from RawQuerySet
  • 9. • Django provide a way to perform query directly to the db via django.db.connection: https://docs.djangoproject.com/en/1.7/topics/db/sql/#executing-custom-sql-directly • You can execute either SELECT, INSERT, DELETE or UPDATE but you can’t use django’s models. • Alternatively you can use a completely different ORM like SQLAlchemy to manage your database. • Both these methods cannot be compatible with many of the built-in features of django. Use Python DB API or other ORM
  • 10. Constraints Model instances ORM query and filtering on the same model ORM relationship queries ORM Insert, Update and Delete Operations Django Admin Django Migrate Inspectdb • Every model must have only one field with PrimaryKey = True • Inspectdb runs across all tables in the schema • Manually check the models compliance YES YES YES If the related models are ORM query compliance YES YES YES if managed = True Manually created models from tables • Every model must have only one field with PrimaryKey = True • You have to create a model for each needed table YES YES YES If the related models are ORM query compliance YES YES YES if managed = True Manually created unmanaged models from views • Every model must have only one field with PrimaryKey = True (easly done inside sql with row_count) • Database write permission needed YES YES YES If the related models are ORM query compliance NO YES but read only NO RawQuerySet • Every model must have only one field with PrimaryKey = True (easly done inside sql with row_count) • You have to write raw sql inside python’s scripts YES NO, you have to write every query method by yourself YES If the related models are ORM query compliance NO NO NO Python DB API or other ORMs • You have to do all by hand!!! NO NO NO NO NO NO Database integrations summary