【问题标题】:Django : save a new value in a ManyToManyFieldDjango:在 ManyToManyField 中保存一个新值
【发布时间】:2009-08-31 10:06:54
【问题描述】:

我提供了我的代码的详细信息:我不知道为什么我的桌子是空的(在调用save_model 之后它似乎是空的,但我不确定)。

class PostAdmin(admin.ModelAdmin):
    def save_model(self, request, post, form, change):
        post.save()

        # Authors must be saved after saving post
        print form.cleaned_data['authors'] # []
        print request.user # pg
        authors = form.cleaned_data['authors'] or request.user
        print authors # pg
        post.authors.add(authors)

        print post.authors.all() # [<User: pg>]

        # But on a shell, table is empty. WTF ?! : 
        # select * from journal_post_authors;
        # Empty set (0.00 sec)

【问题讨论】:

  • django 管理视图发生在事务中,如果抛出异常则回滚。结果页面是否正常呈现?另一种可能性可能是我们都碰巧犯的一些错误:您是否在 shell 会话中查询了正确的数据库?数据库是否可以被 django 进程写入?

标签: python django save add manytomanyfield


【解决方案1】:

您需要在 post.authors.add(authors) 之后再次保存帖子。

【讨论】:

  • 不,你不知道 - 我怀疑 form.cleaned_data['authors'] 应该是用户对象时的字符串
  • 我很确定 af 在这里是正确的,post.authors 不会被保存到数据库中,除非 post.save() 被调用(这反过来又会调用 save_m2m())。
  • save_m2m 是 ModelForm 方法,不是模型方法 docs.djangoproject.com/en/dev/topics/forms/modelforms/…
【解决方案2】:

我找到了解决方案。我刚刚更改了cleaned_data 中的值,它可以工作:

if not form.cleaned_data['authors']:
    form.cleaned_data['authors'] = [request.user]

感谢您帮助我。 :)

【讨论】:

    【解决方案3】:

    我不知道您使用的是什么类型的字段,但那里不应该有其中一个吗? (或类似的东西)

    author = form.cleaned_data['authors']
    User.objects.get(id=author)
    

    【讨论】:

    • 假设他正在使用表单中的某种多选小部件,form.cleaned_data['authors'] 中返回的值应该是用户 ID,因此他不需要再次调用数据库。在任何一种情况下,他的 cmets 都清楚地表明 form.cleaned_data['authors'] 是空的,所以他从请求中追加了用户(authors = form.cleaned_data['authors'] 或 request.user),所以很友好一个有争议的问题。
    猜你喜欢
    • 2014-01-21
    • 2019-02-06
    • 1970-01-01
    • 2012-11-25
    • 2016-07-29
    • 2011-01-12
    • 2020-05-11
    • 2013-04-09
    • 1970-01-01
    相关资源
    最近更新 更多