Search code examples
pythondjangomany-to-many

The right way to set the default value of a ManyToMany field in django


What is the right way to set the default value of a many2many field? This is what I tried below but it is not working. I know that I could override the save method, but wouldn't that be called every time the model gets updated? I want to only set the initial values of the model every time an instance is created.

def default_values():
     return [c.id for c in SomeOtherModel.objects.filter(otherfield__isnull = True)]


class SomeModel(models.Model):
    somefield = models.ManyToManyField('SomeField', default=default_values)
    semeotherfield = models.ForeignKey('SomeOtherField')

I am using django 1.8


Solution

  • You can override save method, and inside that insert a check if primary key is empty or not. If it's empty - this is creation of object.

    Also you can connect to post save signal - there is attribute telling you if this is creation of object or not.