concepts in django

17
Concepts in Django Douwe van der Meij Goldmund, Wyldebeast & Wunderliebe [email protected] github.com/douwevandermeij

Upload: meij200

Post on 08-Jul-2015

487 views

Category:

Technology


1 download

DESCRIPTION

Decouple Django apps with business logic to have better reusability.

TRANSCRIPT

Page 1: Concepts in Django

Concepts in Django

Douwe van der Meij

Goldmund, Wyldebeast & Wunderliebe

[email protected]/douwevandermeij

Page 2: Concepts in Django

Project

INSTALLED_APPS = ( ... 'crm', 'webshop', ...)

Page 3: Concepts in Django

Dependencies

crm

webshop

Customer

Order

● Inter-app foreign key constraint

● How to reuse webshop without crm?

Project

OrderLine

account_nr

order_nr

Page 4: Concepts in Django

Define:

● Producers○ Contain data

● Consumers○ Don’t contain data○ Need a producer

Concepts

Producer

Consumer

Page 5: Concepts in Django

Customer concept

The concept we’re talking about:

● A customer○ Has a number

Page 6: Concepts in Django

Applications with concepts

crm

Customer

webshop

Customer Order

Producer

Consumer

account_nrProject

OrderLinenumber

Page 7: Concepts in Django

Define Producers

CONCEPTS = { 'CustomerConcept': { 'crm.models.Customer': { 'number': 'account_nr', }, },}

● Map to existing models

Conceptname

Producer model

Field mapping

Page 8: Concepts in Django

Consume

class Order(models.Model): customer = models.ForeignKey(CustomerConcept) order_nr = models.IntegerField()

Page 9: Concepts in Django

Dependenciescrm

Customer Project

concepts

CustomerConcept

webshop

Customer

Order

● ORM level

Page 10: Concepts in Django

Dependencies

webshop

Customer

Order

crm

Customer Project

● Database level

Page 11: Concepts in Django

The magic (1/4)

from django.conf import settings

for concept_name, mapping in settings.CONCEPTS.items(): for klass, fields in mapping.items(): ...

● The concepts app○ Loops over settings.CONCEPTS

Page 12: Concepts in Django

The magic (2/4)

from concepts.util import load_class

...concept = type( concept_name, (load_class(klass),), { '__module__': __name__, 'Meta': type('Meta', (), {'proxy': True}), },)...

● Create a dynamic class● With proxy = True in Meta

Page 13: Concepts in Django

The magic (3/4)

...for _property, _field in fields.items(): if not hasattr(concept, _property): setattr( concept, _property, property( lambda self: getattr(self, _field), lambda self, value: setattr(self, _field, value), ), )...

● Create properties for all fields

Page 14: Concepts in Django

The magic (4/4)

import concepts

...setattr(concepts, concept_name, concept)

● Bind the concept to the concepts module

Page 15: Concepts in Django

● Concepts make apps reusable○ Without dependencies

● The only dependency○ Is a concept

● The concept producer○ You may choose yourself○ On existing apps

Conclusion

Page 17: Concepts in Django

Thank you!Douwe van der Meij

Goldmund, Wyldebeast & Wunderliebe

[email protected]/douwevandermeij