views:

22

answers:

1

I have two models (say A and B) which are independent and have independent methods. I want to add some methods that operate on both models though.

for example, addX() will create an object from both models A and B.

What's the best way to structure code in this situation, since it doesnt make sense to have the method belong to either of the models methods. Is the standard to write a service for the kind of 'abstract' model?

A: 

I am not sure I fully understand your question. Are you asking about where to put the common methods or are you asking about how to call one method to act on two classes?

If you just need to have common methods, then I would have an abstract parent model that both models subclass:

class ParentModel(models.Model):

    class Meta:
        abstract = True

    def some_shared_method(self):
        ...

class A(ParentModel):
    ...

class B(ParentModel):
    ...

the abstract meta option tells Django to not create any actual db tables for ParentModel. It is just there to hold the methods.

Check this out for further details: http://docs.djangoproject.com/en/dev/topics/db/models/#id6

Hassan
That's exactly what i was looking for... i didnt want to make a service but that does what i need. Thanks!
Duncan
You're welcome!
Hassan