Reputation: 1885
In my models.py, I have a couple classes, and a couple manager classes.
I have some methods that are general methods used by the model, but not necessarily a part of it.
For example:
def profile_photo_upload_loc(instance, filename):
return "profile_photo/%s/%s" % (instance.user, filename)
class Profile(models.Model):
profile_photo = models.ImageField(
upload_to=profile_photo_upload_loc,
null=True,
blank=True,
width_field='width_field',
height_field='height_field',
verbose_name='Profile Image',
)
Is it okay to have standalone functions outside of classes in the models file? When is it appropriate and when should the functions be inside the class?
Upvotes: 2
Views: 153
Reputation: 338
Django and python, in general, are much more permissible with this kind of liberal approach.
I myself prefer to keep inside model methods that pertain only to it. Like "what is the age of this person?" You take his birthday and counts. Simple as that, but you can use a more Java approach and keep all methods and other business rules and logic into services. I've found that it is best to emulate a Java project when dealing with a python project that I believe that may grow big, but keeping most scripts self-contained and communicating with a good API.
Also, I keep a testing process for each script because python won't tell you that you wrote one extra L when calling the method canceled()
, or if the method still exists inside a class in another file that will be executed passing the function and parameters by reference.
Upvotes: 2
Reputation: 27553
the standalone functions are those functions which can be used in multiple models, like the function you have written can be used in other model image upload,
function those which are written inside a model class are the ones which can only be used with that models instance and not with other models,
if you try to use a function with other model instance it will give an error
Upvotes: 5