在Django中设置ManyToMany字段的默认值的正确方法 [英] The right way to set the default value of a ManyToMany field in django

查看:529
本文介绍了在Django中设置ManyToMany字段的默认值的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置many2many字段的默认值的正确方法是什么?这是我在下面尝试的,但是没有用.我知道我可以覆盖save方法,但是每次更新模型时都不会调用该方法吗?我只想在每次创建实例时设置模型的初始值.

What is the right way to set the default value of a many2many field? This is what I tried below but it is not working. I know that I could override the save method, but wouldn't that be called every time the model gets updated? I want to only set the initial values of the model every time an instance is created.

def default_values():
     return [c.id for c in SomeOtherModel.objects.filter(otherfield__isnull = True)]


class SomeModel(models.Model):
    somefield = models.ManyToManyField('SomeField', default=default_values)
    semeotherfield = models.ForeignKey('SomeOtherField')

我正在使用Django 1.8

I am using django 1.8

推荐答案

您可以覆盖save方法,并在其中插入一个检查主键是否为空的方法.如果为空-这是对象的创建.

You can override save method, and inside that insert a check if primary key is empty or not. If it's empty - this is creation of object.

还可以连接到保存后的信号-属性告诉您这是否是对象的创建.

Also you can connect to post save signal - there is attribute telling you if this is creation of object or not.

这篇关于在Django中设置ManyToMany字段的默认值的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆