我确信这是我看不到的愚蠢,但这就是我所拥有的
def save(self, *args, **kwargs):
print self.sites.all()
super(Article, self).save(*args, **kwargs)
self.sites.add(Site.objects.get(pk=1))
print self.sites.all()
打印
[<Site: site2.co.nz>, <Site: site3.co.nz>]
[<Site: site2.co.nz>, <Site: site3.co.nz>, <Site: site1.co.nz>]
但是{m2}关系中没有site1.co.nz
。{/ p>
答案 0 :(得分:3)
看起来django admin会单独保存m2m,这会在我的自定义保存方法中清除m2m数据。
class MyModelAdmin(admmin.ModelAdmin):
def save_related(self, request, form, *args, **kwargs):
super(ArticleAdmin, self).save_related(request, form, *args, **kwargs).
obj = form.instance
obj.sites.add(Site.objects.get(id=1))