Search code examples
djangodjango-modelsmanytomanyfielddjango-1.8

Default Value Many To Many Field doesn't work, Django 1.8


I have following model:

class Editor(models.Model):
    nombre = models.CharField(max_length=30)
    domicilio = models.CharField(max_length=50)
    #....

class Autor(models.Model):
    nombre = models.CharField(max_length=30)
    apellido = models.CharField(max_length=40)
    email = models.EmailField(blank=True, verbose_name='e-mail')
    #....

def defaultM2M():
    return [Autor.objects.first().pk]

class Libro(models.Model):
    titulo = models.CharField(max_length=100)
    autores = models.ManyToManyField(Autor, default=default2M2)
    editor = models.ForeignKey(Editor, default=Editor.objects.filter(pk=1))

I have a function named defaultM2M to change default value in my ManyToMany attribute for 'Libro', so the issue is when I create a new object 'Libro', this is relationated with my default Autor, no matter if I choose another Autor, My object 'Libro' is create with 2 'Autor' objects, default Autor and chosen Autor. How can set Autor default without this issue?

Thanks


Solution

  • Looking at the Django docs default doesn't seem to be an option for ManyToMany fields. You can however overload the save() method to achieve what you want:

    def save(self, *args, **kwargs)
        if 'autores' not in kwargs:
             kwargs['autores'] = defaultM2M()
        super(Libro, self).save(*args, **kwargs)