Best practices for Django model lookup

160 views Asked by At

I've got a Django models.py which declares a bunch of different classes, including some abstract, and they're related to each other via a variety of ForeignKey, OneToOne, and ManyToMany relationships. Some of the models imply interactions with other machines - so I use Django's signals to watch changes to the relevant models, and inform remote machines of changes that effect them. So far, so good.

Since there are a bunch of signals and a bunch of models, I've put the signals in a separate file (signals.py), and defined a couple of functions to register & unregister them as a group. The end of models.py just calls the register_all() and everything happens automagically. If something needs to happen without sending the remote signals (e.g. unit tests), I can call unregister_all() before hand, then register_all() once I'm done with the weird block. I like splitting the signals from the models because it makes it easier for a programmer to find what she's looking for.

This does, however, lead to some oddness with referencing the models in signals.py, since I occasionally need to traverse a few relationships. The signals take arguments (sender, **kwargs), and (depending on the signal), kwargs can include items "instance" and/or "model". Still good - this gives my code a solid starting point for any lookups it needs to do.

Now, to the actual question: Is there a preferred way to chain 3-5 steps away? I have a choice between patterns get_model('myapp', 'MyModel') and MyModel = sender.parent.field.rel.to, both of which work fine. Is there a reason to choose one over the other? I'd like to maximize code readability and make the changes as easy as possible if relationships or model names change.... And of course, fast & reliable operation is preferred.

0

There are 0 answers