What is the proper way to create M2M relationships during a post-save signal in the admin panel? I have the below code. It successfully creates two Articles
and a Blog
but does not save the relationship between the two.
## models.py
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class Article(models.Model):
title = models.CharField(max_length=250)
class Blog(models.Model):
title = models.CharField(max_length=250)
articles = models.ManyToManyField(Article, blank=True)
def set_related_articles(self):
article_titles = ['a', 'b']
for title in article_titles:
_blog = Article(title=title)
_blog.save()
self.articles.add(_blog)
@receiver(post_save, sender=Blog)
def blog_post_save(sender, instance, **kwargs):
instance.set_related_articles()
## admin.py
from django.contrib import admin
from .models import Blog
@admin.register(Blog)
class BlogUploadAdmin(admin.ModelAdmin):
pass