2

I have the following model:

class Product(models.Model):
    provinces = models.ManyToManyField('Province', related_name='formats')

By default, products can be sold in every province. How can I define the model "Product" so that every product created has all provinces by default?

Thanks!

M.javid
  • 6,387
  • 3
  • 41
  • 56
Michael
  • 1,557
  • 2
  • 18
  • 38
  • This could do the job: [post_save](https://docs.djangoproject.com/en/1.8/ref/signals/#post-save) – Gocht Jul 24 '15 at 19:12

4 Answers4

7

Use the default key. You can't directly set default model values to an iterable like a list, so wrap them in a callable, as the Django documentation advises: https://docs.djangoproject.com/en/1.8/ref/models/fields/

def allProvinces():
    return provincesList

provinces = models.ManyToManyField('Province', related_name='formats', default=allProvinces)
Sam Holladay
  • 113
  • 1
  • 7
  • I know this is old, but I stumbled onto this answer first and eventually [this (old and "unresolved") ticket](https://code.djangoproject.com/ticket/2750). I personally had to use the post_save signal suggered by @Gocht – tgrandje Sep 16 '20 at 12:03
4

You need to use post_save signal.

You can not use default field option for many-to-may fields as mentioned here

1

You cannot directly add a list to M2M directly, you should first get the objects :

def allProvinces():
    provinceList = Province.objects.all()
    return provinceList

And then add the default=allProvinces :)

MrAch26
  • 13
  • 3
1

Expanding from https://stackoverflow.com/a/32068983/1581629 I did this:

class Product(models.Model):
    ...
    def save(self, *args, **kwargs):
        created_flag = False
        if not self.pk:
            created_flag = True
        super().save(*args, **kwargs)
        if created_flag:
            self.provinces = Province.objects.all()
Matteo Gamboz
  • 373
  • 3
  • 11