4👍
You may not use a many to many relation on a model instance that doesn’t have a primary key.
- Save the model, to enable m2m relations
- Save your other model, to enable m2m relations on the other side as well
- 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()
- [Django]-Bin/python3: cannot execute binary file: Exec format error
- [Django]-Django-cors-headers does not allow a request from an allowed origin
- [Django]-Crispy-forms InlineRadios don't show my model state
Source:stackexchange.com