[Django]-Django – initialize model fields including manytomanyfields

4👍

You may not use a many to many relation on a model instance that doesn’t have a primary key.

  1. Save the model, to enable m2m relations
  2. Save your other model, to enable m2m relations on the other side as well
  3. Use .add(), for example yourmodel.bars.add(othermodel)

If you want to set default, initial data, you should use fixtures.

👤jpic

3👍

You can do this using django’s signals. Every time an instance of your Foo model is created, also create the other information you require:

class Foo(models.Model):
    ...

from django.db.models.signals import post_save 
from signals import create_initial_data
post_save.connect(create_initial_data, sender=Foo)

and in a file called signals.py:

from models import Bar
def create_initial_data(sender, instance, created, raw):
    if created and sender == 'Foo':
        bar_1 = Bar(...)
        bar_2 = Bar(...)
        ...
        bar_1.save()
        bar_2.save()
        ...
        instance.bars.add(bar_1, bar_2, ...)
        instance.save()

Leave a comment