Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ManyToMany all values by default

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!


1 Answers

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)
like image 111
Sam Holladay Avatar answered Oct 31 '25 08:10

Sam Holladay