Friday, May 6, 2011

where to put method that works on a model

I'm working with Django.

I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.

like obj.get_current_side(username)

I've added this to the actual Argument model like this

 def get_current_side(self, user):
        return self.argument_set.latest('pub_date').side

I am starting to think this doesn't make sense because there may not be an instance of an Argument. Is this a place I would use a class method? I thought about making a util class, but I'm thinking that it makes sense to be associated with the Argument class.

From stackoverflow
  • I think what you are looking for are model managers.

    Django docs on managers with managers you can add a function to the model class instead of a model instance.

  • It would make more sense to have instance methods on the User model:

    def get_current_side(self):
        try:
            return self.arguments.latest('pub_date').side
        except User.DoesNotExist, e:
            return None
    

    You can do this by extending the User model as explained here:

    Edit: I'm not exactly sure which exception gets thrown.

  • This should be a method on a custom model manager:

    # in models.py
    class ArgumentManager(models.manager.Manager):
        def get_current_side(self, user):
            try:
                return self.filter(user=user).latest('pub_date').side
            except Argument.DoesNotExist:
                return None
    
    class Argument(models.Model):
        # fields etc...
    
        objects = ArgumentManager()
    
    
    # Calling:
    
    side = Argument.objects.get_current_side(user)
    

    Alternaticely you can extend contrib.auth.user and add get_current_size() on it. But I wouldn't mess with it until I'm very confident with Django.

    BTW: Most of the code in this page is wrong; for example user variable is not used at all on the OP's snipplet.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.