在多对多模型中创建新的目标实例时,更新源模型的每个实例的推荐方法是什么?
Whats the recommended way to update every instance of a source model when a new target instance is created in a manytomany model?
我有一个网站,我想在其中显示基本的 html table,如下所示:
Product_Name | Attribute_1 | Attribute_2
-----------------------------------------
Soap | True | True
Shampoo | False | True
所以我创建了 类 Product
和 Attribute
具有多对多关系。
Models.py
class Product(models.Model):
name = models.CharField(max_length=10)
attributes = models.ManyToManyField(on_delete='CASCADE')
class Attribute(models.Model):
name = models.CharField(max_length=1, default='N')
所以我有两个属性实例 - Attribute_1 和 Attribute_2。
当我创建一个新属性 (Attribute_3) 时,有没有一种方法可以将我所有具有 link 的 Product 实例的关系更新到新属性?
我知道 Django 通过 table 为 m2m 关系创建了一个。根据 docs,我知道我可以这样做:
for prod_obj in Product.objects.all():
prod_obj.add(new_attribute_object)
但是我如何确保每次创建属性对象时都发生这种情况automatically/consistently?
您应该为您的 Attribute
模型编写自定义 save
方法,a) 检查 Attribute
对象是否是第一次创建; b) 如果是这样,将 Attribute
添加到数据库中的每个 Product
。有关编写自定义 save
方法的更多信息,请参阅 this post。
我有一个网站,我想在其中显示基本的 html table,如下所示:
Product_Name | Attribute_1 | Attribute_2
-----------------------------------------
Soap | True | True
Shampoo | False | True
所以我创建了 类 Product
和 Attribute
具有多对多关系。
Models.py
class Product(models.Model):
name = models.CharField(max_length=10)
attributes = models.ManyToManyField(on_delete='CASCADE')
class Attribute(models.Model):
name = models.CharField(max_length=1, default='N')
所以我有两个属性实例 - Attribute_1 和 Attribute_2。
当我创建一个新属性 (Attribute_3) 时,有没有一种方法可以将我所有具有 link 的 Product 实例的关系更新到新属性?
我知道 Django 通过 table 为 m2m 关系创建了一个。根据 docs,我知道我可以这样做:
for prod_obj in Product.objects.all():
prod_obj.add(new_attribute_object)
但是我如何确保每次创建属性对象时都发生这种情况automatically/consistently?
您应该为您的 Attribute
模型编写自定义 save
方法,a) 检查 Attribute
对象是否是第一次创建; b) 如果是这样,将 Attribute
添加到数据库中的每个 Product
。有关编写自定义 save
方法的更多信息,请参阅 this post。