James L.
James L.

Reputation: 1153

Remove first 3 characters from a field in the database

I've doctor entries in my database and I want to remove the first 3 characters from their name.

class Doctor(models.Model):
    name = models.CharField(max_length=1300)
    specialization = models.ForeignKey(Specialization)

    def __unicode__(self):
      return u"%s %s" % (self.name, self.specialization)

    def get_absolute_url(self):
        from django.core.urlresolvers import reverse
        return reverse('k.views.showDocProfile', args=[str(self.id)])

I've quite a few entires so removing then manually is not ideal.

Upvotes: 0

Views: 70

Answers (1)

bakkal
bakkal

Reputation: 55448

One time all-db change:

for doctor in Doctor.objects.all():
   doctor.name = doctor.name[3:]
   doctor.save()

If you just need to mask the name for some use cases only, you can use a property field in your model

class Doctor(Model):
   name = CharField(...)

   @property
   def masked_name(self):
       return self.name[3:]

   # To access to property you just use doctor.masked_name on an instance of the Doctor class (it's a property, you don't have to call doctor.masked_name())

Upvotes: 1

Related Questions