On Wed, Mar 5, 2014 at 1:03 PM, Domagoj Kovač <doctorko...@gmail.com> wrote:
> Hi Guys,
>
> I have a model called Calculation, this model has fields that are calculated
> and saved to the database, this model also hold some common calculation
> functions.
>
> I also have two other classes TrailerCalculation and TruckCalculation they
> both calculate values of the fields that will be saved to Calculation, they
> calculate same properties but in a different way. So i extended Calcution
> with TrailerCalculation and TruckCalculation. Is there some way that child
> classes don't need to be models even though they inherit a class that
> inherits a model.Models? I tried with class Meta: abstract = True but this
> gives me some kind of strange error.

Your derived classes are models, and they should be models. What they
shouldn't be is have different tables for each model type, there
should be one table that all instances are stored in to, as the data
for each Calculation instance, regardless of type, is the same.

This is a common idiom in ORMs, and is called Single Table Inheritance:

http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html

Django doesn't support STI, but that doesn't really matter, you can
get the same behaviour by using composition rather than inheritance,
something like this:

CALC_TYPE_MAP = {
  'trailer': TrailerCalculation,
  'truck': TruckCalculation,
}

class Calculation(models.Model):
    .....
    #
    def calculate(self):
       calculator = CALC_TYPE_MAP[self.calculation_type]()
       calculator.calculate(self)

TrailerCalculation and TruckCalculation do not derive from
Calculation, they are simply objects that provide functionality to
Calculation. This approach is called "Composition over inheritance".

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAFHbX1%2BcUr-ub91_jBuhA7bkoco6e-bT358e5bGJBJfyLg6kGA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to