0

If I have a Person modle as below:

class Person
    first_name = models.CharField
    last_name = models.CharField

I want to create a composite attribute full name, which would be a combination of first and last name.

full_name = self.first_name + ' ' + self.last_name

Also, whenever a the first name in the person model is modified the full_name should be automatically update.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
Joel James
  • 3,870
  • 9
  • 32
  • 47

2 Answers2

4

Just make it a property on the model.

class Person(...):
   ...
  @property
  def full_name(self):
    return u'%s %s' % (self.first_name, self.last_name)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • How could I update this property(full_name) when a change is made to the first name or last name? Also, is there a way to set unique constrain on this property? – Joel James May 20 '13 at 23:00
  • 1
    It would never need updating and it would never need a constraint since it doesn't exist in the database. – Ignacio Vazquez-Abrams May 20 '13 at 23:02
  • Is there a way to create a composite attribute which could be saved to the database? – Joel James May 20 '13 at 23:05
  • 1
    Sure, [but that would be silly.](http://en.wikipedia.org/wiki/Database_normalization) – Ignacio Vazquez-Abrams May 20 '13 at 23:08
  • This model was just an example. In my project I am creating a natural key based on three other fields in the modle. If I am not storing my composite attribute to the database I wont be able to perform queries on the composite attribute. That is one of the reason I want this composite attribute to be saved to the database. – Joel James May 21 '13 at 00:02
  • 1
    Joel I think you should ask the _actual_ question which I believe is - _"How do I define a composite key in django models?"_ and the answer to that is [here](http://stackoverflow.com/questions/2270808/compound-composite-primary-unique-key-with-django) (also answered by Ignacio). – Burhan Khalid May 21 '13 at 06:46
1

I figured out that this could be done by overriding the custom save method.

class Person
    first_name = models.CharField()
    last_name = models.CharField()
    full_name = models.CharField()

def save(self, *args, **kwargs):
    self.full_name = self.first_name + ' ' + self.last_name
    super(Person, self).save(*args, **kwargs)
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
Joel James
  • 3,870
  • 9
  • 32
  • 47