views:

61

answers:

2

I have a certain class structure in my app, that currently utilizes django for presentation. I was not using the model layer at all, - the database interaction routines are hand-written.

I am, however, considering the possibility of actually using django to its full potential and actually using the database-abstraction layer. The question is how to best integrate my existing class structure with the model layer.

An example class:

class UpperClass(base):
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2
        # attr1 and attr2 are actually instances of, say, 
        # CustomType1 and CustomType2

Sow here is how am I going to map this to a django model:

class UpperClass(models.Model):
    attr1 = CustomType1Field(...)
    attr2 = CustomType2Field(...)

That's straightforward enough - all the serialization and validation stuff is already written, so it will not be hard at all to conjure up the custom field classes for CustomType1 and CustomType2.

The real question is, where do I put the custom (not-database-related) behaviour of the actual UpperClass. In my understanding, models are there for "getting things in and out of the database", but where does the behaviour go then? Do I embed the non-database-related methods in the Model instances of the UpperClass? Really, I am at a loss here. Hope this makes at least partial sense to you.

+1  A: 

It somewhat depends on what specific behavior you want to encode. In most cases, you should try to put per-object behavior into the model class. It's a regular Python class, after all, so you can give it any methods you desire. You do need to account for the persistant nature, of course, e.g. by avoiding additional member data beyond those specified in the schema.

Martin v. Löwis
Suddenly, this makes perfect sense to me. Since model fields (subclasses of models.Field) map back to python types/classes (through to_python()), it doesn't matter how the class instances of UpperClass get initialized, - either through the direct call to __init__ from my code (a = UpperClass(attr1=foo, attr2=bar)) or through the ORM (a = Upperclass.objects.get(...)). Either way, the instance namespace gets populated with attr1 and attr2 initialized to the correct type. Did I understand you correctly?
shylent
Yes: instances of UpperClass are regular Python objects, with regular attributes attr1 and attr2 (read out of the database).
Martin v. Löwis
Thanks a lot for your help.
shylent
A: 

This is largely a philosophical question re: MVC and how you choose to implement it. Arguably there is no right way here, but assuming that you want the model objects to all behave in a certain way regardless of the view that interacts with them, it makes sense to attach this behavior to the model. If the behavior is specific to only a certain view, and there are many other views that interact with the model, then it might make more sense to attach it to the view.

Ben