title: Structuring Django-App to Attach Custom Business Rules to Object Instances
body: <p>I'm torn how to structure my code to accommodate business rules specific to <em>instances</em> of a particular model.</p>
  
  <p>For example. Lets say I have a Contact model with a type field and <code>choices=(('I','Individual'),('C','Company))</code>. Based on the type of model that I have, I might want to have custom methods.</p>
  
  <p>So thinking out loud, something like this would be nice:</p>
  
  <pre><code>class IndividualContact(Contact):
  """ A custom class used for Contact instances with type='I' """
      criteria = Q(type='I')
  
  # The goal here is that Contact is now aware of IndividualContact and constructs
  # objects accordingly.
  Contact.register(IndividualContact)
  </code></pre>
  
  <p>Or even:</p>
  
  <pre><code>class SpecialContact(Contact):
  """ A custom class used for the contact with pk=1 """
      criteria = Q(pk=1)
  </code></pre>
  
  <p>At which point I have a nice home for my special instance specific code.</p>
  
  <p>One of the alternatives I explored is using model inheritance and avoiding things like type fields that impart new behaviors. That way, new classes plug into the existing framework elegantly and you're nicely set up to add custom fields to your different types in case you need them.</p>
  
  <p>In my case I have a resource crediting system on the site that allows me to say things like "You may only have 2 Listings and 20 Photos". Individual resource types are rationed, but there is a generic credit table that gives you credits for various content types. The logic that goes into counting up your Listings and Photos varies based on the type of object you're working with.</p>
  
  <p>I.E.:</p>
  
  <pre><code>listing_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Listing), user=user, credit_amt=2)
  
  # Should subtract **active** listings from current sum total of Listing credits.
  listing_credit.credits_remaining()
  
  photo_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Photo), user=user, credit_amt=5)
  
  # Photos have no concept of an active status, so we just subtract all photos from the current sum total of Listing credits. 
  # Also, the Photo might be associated to it's user through a 'created_by' field whereas
  # Listing has a user field.  
  photo_credit.credits_remaining()
  </code></pre>
  
  <p>My current approach is separate classes but I'd like to reduce that boilerplate and he necessity of creating N separate tables with only a <code>credit_ptr_id</code>.</p>