Search code examples
pythondjangomanytomanyfield

Whats the recommended way to update every instance of a source model when a new target instance is created in a manytomany model?


I have a website where I want to display a basic html table like so:

Product_Name | Attribute_1 | Attribute_2
----------------------------------------- 
Soap         | True        | True 
Shampoo      | False       | True

So I have created the classes Product and Attribute with a ManyToMany relationship.

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')

So I have two Attribute instances - Attribute_1 and Attribute_2.

When I create a new attribute (Attribute_3), is there a way I can update the relationships of all of my Product instances with a link to the new Attribute?

I know that Django creates a through table for m2m relationships. According to the docs, I know I can do something like:

for prod_obj in Product.objects.all(): prod_obj.add(new_attribute_object)

But how do I ensure this happens automatically/consistently every time I create an attribute object?


Solution

  • You should write a custom save method for your Attribute model that a) checks to see whether the Attribute object is being created for the first time; and b) if so, adds that Attribute to each Product in your database. For more information on writing a custom save method, see this post.