K.J Fogang Fokoa
K.J Fogang Fokoa

Reputation: 219

How to convert a models.IntegerField() to an integer?

i try to assign a default value to an attribute of my table. This value is the value of another attribute. Here is an excerpt

nombre_etudiant = models.IntergeField()
place_disponible =models.IntegerField(default=int(nombre_etudiant))

I tried with to_pythyon(), we told me : 'to_python' is not defined How to do !?

Upvotes: 2

Views: 2793

Answers (2)

Slava
Slava

Reputation: 1997

You need override the save() method of the model class.

class MyModel(models):
   nombre_etudiant = models.IntergeField()
   place_disponible =models.IntegerField()

   def save(self, *args, **kwargs):
       if not self.place_disponible:
           self.place_disponible = int(nombre_etudiant)
           super(Subject, self).save(*args, **kwargs)

Upvotes: 1

Akhil Batra
Akhil Batra

Reputation: 610

you can add an attribute initialization inside __init__ method.

The right way to do this will be

class Foo(models):
    nombre_etudiant = models.IntergeField()
    place_disponible =models.IntegerField(blank=True,null=True)

    def __init__(self,*args,**kwargs):
        super(Foo, self).__init__(*args, **kwargs)
        if self.place_disponible is None:
            self.place_disponible = self.nombre_etudiant

Upvotes: 1

Related Questions