Where to put the method that works on the model

I am working with Django.

I have a model called Agrument. Arguments have parties and owners. I have a function that returns back the side of the last argument of a specific user.

like obj.get_current_side (username)

I added this to an actual Argument model like this

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

      

I'm starting to think this doesn't make sense because there can't be an instance of Argument. Is this where I would use a class method? I was thinking about creating a util class, but I think it makes sense to associate with the Argument class.

+1


a source to share


3 answers


It would make more sense to have instance methods in the model User

:

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 model User

as described here:



Edit: I don't know exactly what kind of exception will be thrown.

+2


a source


This should be the method for the 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)

      



Alternatively, you can expand contrib.auth.user

and add get_current_size()

on it. But I wouldn't argue with him until I'm confident about Django.

BTW: Most of the code on this page is wrong; for example the variable user

is not used at all in the OP's snipplet.

+1


a source


I think you are looking for model managers.

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

0


a source







All Articles