> Does the function operate on a single model? Will it be run when you
> already have the instance of the model?

To add to Collin's comment, it doesn't even have to operate on a
single model.  It simply has to be a property of the model
itself.  Thus, it would make sense to have something like


  def Invoice(Model):
     customer = ForeignKey(Customer)
     invoice_dt = DateField(...)
     paid = BooleanField(default=False)
     def total_cost(self):
        tax_rate = self.customer.tax_rate
        i = 0
        for lineitem in self.line_items:
           i += lineitem.total_cost(tax_rate)

  def LineItem(Model):
     invoice = ForeignKey(Invoice, related_name="line_items")
     description = CharField(...)
     qty = IntegerField(...)
     cost = DecimalField(...)
     taxable = BooleanField(...)
     def total_cost(self, tax_rate):
        if not self.taxable: tax_rate = 1
        return self.qty * self.cost * tax_rate


Note that each model has a total_cost() method, which is clearly
associated with calculating the "total cost" of the model.  In
the case of the Invoice.total_cost(), it references sub-fields
within it such as the reverse foreign key collection "line_items"
and the customer associated with the given Invoice.

I've also made methods based not on the "request" object (which
is generally a bad smell as Alex mentioned), but on the user
object contained within the request:

  class MyModel(Model)
     ...
     def allowed_objects(cls, user):
        return MyModel.filter(fieldname__user__id = user.id)
     allowed_objects = classmethod(allowed_objects)

so I can use

  MyMode.allowed_objects(request.user).get(id=42)

where each model knows how to filter itself based on what a given
user can see.

-tim





--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to