Home > Enterprise >  Why does the variable give me a TypeError but the function doesn't?
Why does the variable give me a TypeError but the function doesn't?

Time:09-23

I'm trying to run the following code but "full_name" gives me the following error.

TypeError: unsupported operand type(s) for : 'CharField' and 'str'

from django.db import models

class user(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

    full_name = first_name   ' '   last_name

    def __str__(self):
        return self.full_name

When I change the "full_name" from a variable to a function, the TypeError goes away and my code works fine.

from django.db import models

class user(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    
    def full_name(self):
        return self.first_name   ' '   self.last_name

    def __str__(self):
        return self.full_name()

Why does the variable give me a TypeError but the function doesn't? Don't they do the same thing?

CodePudding user response:

It gives error because full_name is actually a variable in user class. But fucntion is returning a string. Class user never actually runs so you cant's define a variable which doesn't subclass django.models.

CodePudding user response:

Statements on class level are evaluated on start up. Statements in methods are evaluated when the method is called.

In the first example the expression is evaluated on start up; against the class attribute values. Effectively, you are doing models.CharField(max_length=200) ' ' models.CharField(max_length=200), but you can't concatenate a CharField with a string.

In the second example the expression is performed when the method is called on an instance; against the values of both fields, which are strings.

  • Related