Django ManyToMany all values by default

前提是你 提交于 2020-12-16 05:31:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!