Home > front end >  Functions under django model class
Functions under django model class

Time:02-02

I'm working on django models. At the design level I'm confused if I can implement functions inside model class. If I can implement then what kind of functions should be going inside and what kind of functions shouldn't. I couldn't find a document regarding this apart from doc

Or is there any document where I can figure out about this?

CodePudding user response:

Yes, of course you can create functions inside the model class. It's highly recommended especially for things that you have to calculate specifically for objects of that model. In example it's better to have function that calculates let's say Reservation time. You don't have to put that info inside database, just calculate only when it's needed:

class Reservation(models.Model):
    valid_to = models.DateTimeField(...)

    def is_valid(self):
        return timezone.now() < self.valid_to

Depending on what you actually need/prefer it might be with @property decorator.

CodePudding user response:

I guess you are asking about the old discussion "Where does the business logic go in a django project? To the views, or the model?"

I prefer to write the business logic inside of the views. But if it happens that I need a special "treatment" of a model several times in multiple views, I turn the treatment inside of the model.

To give you an example:

# models.py
class Customer(models.Model):
    name = models.CharField(max_length=50, verbose_name='Name')


# views.py
def index(request):
    customer = Customer.objects.all().first()
    name = str.upper(customer.name)  # if you need that logic once or twice, put it inside of the view
    return HttpResponse(f"{name} is best customer.")

If you need the logic in multiple views, over and over again, put it inside of your model

# models.py
class Customer(models.Model):
    name = models.CharField(max_length=50, verbose_name='Name')

    @property
    def shouted_name(self):
        return str.upper(self.name)

# views.py
def index(request):
    customer = Customer.objects.all().first()  # grab a customer
    return HttpResponse(f"{customer.shouted_name} is best customer.")

def some_other_view(request):
    customer = Customer.objects.all().first()  # grab a customer
    customer_other = Customer.objects.all().last()  # grab other customer
    return HttpResponse(f"{customer.shouted_name} yells at {customer_other}")
# see method shouted_name executed in two views independently
  • Related