在管理面板中的保存后信号期间创建M2M关系的正确方法是什么?我有下面的代码。它成功创建了两个Articles
和一个Blog
,但没有保存两者之间的关系。
## 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
答案 0 :(得分:1)