1

Consider this example taken from Querying full name:

class User( models.Model ):
    first_name = models.CharField( max_length=64 )
    last_name = models.CharField( max_length=64 )
    full_name = models.CharField( max_length=128 )
    def save( self, *args, **kw ):
        self.full_name = '{0} {1}'.format( first_name, last_name )
        super( User, self ).save( *args, **kw )

According to Django Model Method this is also possible to be written this way:

class User(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

def _get_full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.first_name, self.last_name)
    full_name = property(_get_full_name)

What's the difference? Which one is recommended?

Community
  • 1
  • 1
Sam R.
  • 16,027
  • 12
  • 69
  • 122

2 Answers2

2

In the first case, full_name is a column in the database. So use this if you need to run database queries against it.

In the second case, it's just a read-only convenience attribute. So it's fine for displaying the name in the admin or elsewhere, but that's about it.

So the question of which to use is really a design decision based on what you need to do with the field. Another common example of this is when you're using a slug field of some kind (where the slug is a URL-friendly version of some text in your model). If you're doing your database lookups based on ids then you may not need to put the slug in the database at all. But if you want to look things up by the slug field, or if you want to preserve the old slug even when the text changes, you'll want to make it a real column.

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
2
class User(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def save( self, *args, **kw ):
        self.first_name = '{0} {1}'.format( self.first_name, self.last_name )
        super( User, self ).save( *args, **kw )

    def _get_full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.last_name, self.first_name)
    full_name = property(_get_full_name)

Well here save method is overriden. So when ever you try to save User object the feild first_name will be saved in format as first_name last_name.

enter image description here

enter image description here

The _get_full_name method just returns combination of User's last_name and first_name when we try to call it using User's Querset object.

>>> from Question.models import *
>>> user_objects = User.objects.all()
>>> for obj in user_objects:
...     print "User's First Name :", obj.first_name
...     print "User's Last Name :", obj.last_name
...     print "User's Full Name :", obj._get_full_name()
...
User's First Name : Tanveer Alam
User's Last Name : Alam
User's Full Name : Alam Tanveer Alam
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43