Django,在自定义保存方法中添加项目到manytomany不在admin中工作

时间:2014-01-23 21:07:05

标签: django django-orm

我确信这是我看不到的愚蠢,但这就是我所拥有的

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>

1 个答案:

答案 0 :(得分:3)

看起来django admin会单独保存m2m,这会在我的自定义保存方法中清除m2m数据。

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_related

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))