Ara Sivaneswaran
Ara Sivaneswaran

Reputation: 375

Django - Inserting related instance

I am trying to change how a model saves and add a field automatically. The field in question is a foreignkey.

here is the code:

def save(self, *args, **kwargs):
    season = Season.objects.order_by('start')[0]
    self.season = season

But it doesn't add anything...

It says success but it doesn't add....

EDIT: Full code:

class Team(models.Model):

GENDER_CHOICES = (
    ('F', 'Féminin'),
    ('M', 'Masculin'),
)

name = models.CharField(max_length=25,verbose_name="nom")
slug = AutoSlugField(unique=True,populate_from='name')
season = models.ForeignKey(Season,verbose_name="saison",editable=False)
association = models.ForeignKey(Association,verbose_name="association")
category = models.ForeignKey(Category,verbose_name="catégorie")
division = models.ForeignKey(Division,verbose_name="division")
gender = models.CharField(max_length=1,choices=GENDER_CHOICES,verbose_name="sexe")

class Meta:
    verbose_name = 'Équipe'
    verbose_name_plural = 'Équipes'

def __str__(self):  # Python 3: def __str__(self):
    return self.name

def save(self, *args, **kwargs):
    season = Season.objects.order_by('start')[0]
    self.season = season
    super(self,Team).save(*args,**kwargs)

Thanks, Ara

Upvotes: 1

Views: 46

Answers (1)

Emanuele Paolini
Emanuele Paolini

Reputation: 10172

at the end of your ‘save‘ method you must call the superclass ‘save‘:

def save(self, *args, **kwargs):
    season = Season.objects.order_by('start')[0]
    self.season = season
    super(MyModelName,self).save(*args,**kwargs)

Upvotes: 2

Related Questions