[ Pobierz całość w formacie PDF ]
.Once a project goes live, chapter 20, Finding and Reducing Bottlenecks, has information on indexanalysis.6.1.4 Be Careful With Model InheritanceModel inheritance in Django is a tricky subject.Django provides three ways to do model inheritance:abstract base classes, multi-table inheritance, and proxy models.WARNING: Django Abstract Base Classes Python AbstractBase ClassesDon t confuse Django abstract base classes with the abstract base classes in the Python stan-dard library s abc module, as they have very different purposes and behaviors.49 Chapter 6: Database/Model Best PracticesHere are the pros and cons of the three model inheritance styles.To give a complete comparison, wealso include the option of using no model inheritance to begin with:Model Inheritance Pros ConsStyleNo model inheritance: if models Makes it easiest to understand at a If there are a lot of fieldshave a common field, give both glance how Django models map to duplicated across models, thismodels that field.database tables.can be hard to maintain.Abstract base classes: tables are Having the common fields in an We cannot use the parent classonly created for derived models.abstract parent class saves us from in isolation.typing them more than once.We don't get the overhead of extratables and joins that are incurred frommulti-table inheritance.Multi-table inheritance: tables Gives each model its own table, so that Adds substantial overhead sinceare created for both parent and we can query either parent or child each query on a child tablechild.An implied model.requires joins with all parentOneToOneFieldlinks parent Also gives us the ability to get to a tables.and child.child object from a parent object: We strongly recommend againstparent.child using multi-table inheritance.See the warning below.Proxy models: a table is only Allows us to have an alias of a model We cannot change the model'screated for the original model.with different Python behavior.fields.Table 6.1: Pros and Cons of the Model Inheritance StylesWARNING: Avoid Multi-Table InheritanceMulti-table inheritance, sometimes called  concrete inheritance, is considered by the authorsand many other developers to be a bad thing.We strongly recommend against using it.We llgo into more detail about this shortly.Here are some simple rules of thumb for knowing which type of inheritance to use and when:If the overlap between models is minimal (e.g.you only have a couple of models that share one50 6.1: Basicsor two obvious elds), there might not be a need for model inheritance.Just add the elds toboth models.If there is enough overlap between models that maintenance of models repeated elds causesconfusion and inadvertent mistakes, then in most cases the code should be refactored so thatthe common elds are in an abstract base class.Proxy models are an occasionally-useful convenience feature, but they re very different fromthe other two model inheritance styles.At all costs, everyone should avoid multi-table inheritance (see warning above) since it addsboth confusion and substantial overhead.Instead of multi-table inheritance, use explicit One-ToOneFields and ForeignKeys between models so you can control when joins are traversed.6.1.5 Model Inheritance in Practice: The TimeStampedModelIt s very common in Django projects to include acreatedandmodifiedtimestamp eld on allyour models.We could manually add those elds to each and every model, but that s a lot of workand adds the risk of human error.A better solution is to write aTimeStampedModelto do the workfor us:E.# core/models.pyfrom django.db import modelsclass TimeStampedModel(models.Model):"""An abstract base class model that provides self-updating ``created`` and ``modified`` fields."""created = models.DateTimeField(auto_now_add=True)modified = models.DateTimeField(auto_now=True)class Meta:abstract = TrueTake careful note of the very last two lines in the example, which turn our example into an abstractbase class:51 Chapter 6: Database/Model Best PracticesE.class Meta:abstract = TrueBy de ningTimeStampedModelas an abstract base class when we de ne a new class that inheritsfrom it, Django doesn t create amodelutils.timestampedmodeltable when syncdb is run.Let s put it to the test:E.# flavors/models.pyfrom django.db import modelsfrom core.models import TimeStampedModelclass Flavor(TimeStampedModel):title = models.CharField(max_length=200)is only creates one table: theflavorsflavordatabase table.at s exactly the behavior wewanted.On the other hand, ifTimeStampedModelwas not an abstract base class (i.e.a concrete base classvia multi-table inheritance), it would also create amodelutilstimestampedmodeltable.Notonly that, but all of its subclasses includingFlavorwould lack the elds and have implicit foreignkeys back toTimeStampedModeljust to handlecreated/modifiedtimestamps.Any reference toFlavorthat reads or writes to theTimeStampedModelwould impact two tables.( ank goodnessit s abstract!)Remember, concrete inheritance has the potential to become a nasty performance bottleneck.isis even more true when you subclass a concrete model class multiple times.Further reading:http://2scoops.co/1.5-model-inheritance52 6.2: Django Model Design6.1.6 Use South for MigrationsSouth is one of those rare third-party packages that almost everyone in the Django community usesthese days.South is a tool for managing data and schema migrations.Get to know South s featureswell.A few South tips:As soon as a new app or model is created, take that extra minute to create the initial Southmigrations for that new app or model [ Pobierz całość w formacie PDF ]

  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • lunamigotliwa.htw.pl
  •