0

Let's I have a model.

class Trips(models.Model):
    from_point   = models.CharField(max_length=50)
    to_point     = models.CharField(max_length=50)
    trip_desc    = models.TextField(max_length=250)
    seats        = models.CharField(max_length=20, blank=True, null=True)
    price        = models.PositiveIntegerField()
    created_time = models.DateTimeField(auto_now_add=True)
    new_attribure= ?

How to create an attribute so when we're creating an instance of Trips it will take part of attributes from_point, to_point + some unique string?

For example:

obj1 = Trips('Moscow', 'Dushanbe', 'Some_description', '4', '100', 'date_time', 'MosDushUniquestring')

In this case it's taking three first characters of from_point, to_point attributes + some unique string. The idea is to have a unique attribute which has some meaning trip reference number.

Jovid Nurov
  • 21
  • 1
  • 7
  • Does this answer your question? [How to add a calculated field to a Django model](https://stackoverflow.com/questions/17682567/how-to-add-a-calculated-field-to-a-django-model) – Harun Yilmaz Nov 06 '19 at 09:59

1 Answers1

0

You can add a string field (CharField/TextField) and modify its value upon save, Like:

def save(self, *args, **kwargs):
    if self.pk:
        //Edit existing object (update)
        self.new_attribure = "some edited value"
    else:
        //Add new object (insert)
        self.new_attribure = "some new value" + self.from_point
    //or you can ignore the add/edit and just apply it on all cases like:
    //self.new_attribure = "my value"
    super(Trips, self).save(*args, **kwargs)
  • Thanks Mr Al-Horani) I've picked this way //or you can ignore the add/edit and just apply it on all cases like: //self.new_attribure = "my value" and It worked. I did not usederstood the difference between you if and else statments. – Jovid Nurov Nov 06 '19 at 12:29
  • Some times you need to add the value only when you are only adding or editing the object, that's why I added the if/else closure. – Yazan M. Al-Horani Nov 07 '19 at 07:57