问题
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:
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)
回答2:
You need to use post_save signal.
You can not use default field option for many-to-may fields as mentioned here
来源:https://stackoverflow.com/questions/31617838/django-manytomany-all-values-by-default