我创建了一个django模型
class Apps(models.Model):
name = models.CharField(max_length=300, default="name")
package_name = models.CharField(max_length=255, default="package_name")
和我可能会也可能不会同时收到(name,package_name)
我的插入查询功能
def func(data):
try:
kwargs = dict(name=data.get('name'),
package_name=data.get('package_name'))
app = Apps.objects.get(**kwargs)
except:
app = Apps(**kwargs)
app.save()
return app
我的问题是
当kwargs = {"name" : None, "package_name": "pkg"}
时采用与名称对应的模型字段中指定的默认值(因为它是None
中的kwargs
)
答案 0 :(得分:1)
Django无法将默认值替换为查询,您必须稍微帮助一下:
在你的模型中定义一些常量:
class Apps(models.Model):
DEFAULT_NAME = 'name'
DEFAULT_PACKAGE_NAME = 'package_name'
name = models.CharField(max_length=300, default=DEFAULT_NAME)
package_name = models.CharField(max_length=255, default=DEFAULT_PACKAGE_NAME)
然后在代码中使用它们:
def func(data):
kwargs = dict(name=data.get('name', Apps.DEFAULT_NAME),
package_name=data.get('package_name', Apps.DEFAULT_PACKAGE_NAME))
return Apps.objects.get_or_create(**kwargs)[0]