使用具有ModelForm的特定数据库 [英] Use a specific database with a ModelForm
问题描述
如果 ModelForm
保存数据,我该如何指定数据库?
Django中的多数据库支持意味着我可以定义更多的数据库默认值
。例如:
#settings.py
DATABASES = {
'default':{
'ENGINE':'django.db.backends.sqlite3',
'NAME':':memory:',
},
}
'staging':{
'ENGINE':'django.db.backends.postgresql_psycopg2',
'HOST':'db.example.com',
# ...
},
}
这允许模型管理器查询不同的数据库从默认值:
从django import models
class Foo (models.Model):
#...
queryset = Foo.objects.using('staging')。all()
一个 ModelForm
子类也与数据库进行交互:
< pre class =lang-python prettyprint-override>
from django import forms
from .models import Foo
class FooImportForm(forms.ModelForm):
class Meta:
model = Foo
fields = [
#...
]
fields = {
#...
}
form = FooImportForm(fields)
form.save()
/ pre> 如何指定 FooModelForm
实例应该使用 staging
数据库当我 form.save()
?我看不到使用('staging')指定相当于的地方。
Model.save
方法接受使用
参数指定数据库:
foo = Foo(fields)
foo.save(using ='staging')
ModelForm.save
方法返回模型
实例:
foo_form = FooImportForm(fields)
pre>
foo = foo_form.save()
可以选择不要提交
ModelForm.save
方法:foo_form.save(commit = False)
把它全部丢下来r:foo_form = FooImportForm(fields)
foo = foo_form.save(commit = False)
foo.save(uses ='staging')
How can I specify the database to use when a
ModelForm
saves its data?The multiple-database support in Django means that I can define more databases than just the
default
. For example:# settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, }, 'staging': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'db.example.com', # … }, }
This allows a model manager to query a different database from the default:
from django import models class Foo(models.Model): # … queryset = Foo.objects.using('staging').all()
A
ModelForm
subclass also interacts with the database:from django import forms from .models import Foo class FooImportForm(forms.ModelForm): class Meta: model = Foo fields = [ # … ] fields = { # … } form = FooImportForm(fields) form.save()
How can I specify that the
FooModelForm
instance should use thestaging
database when Iform.save()
? I can't see a place where to specify the equivalent ofusing('staging')
.解决方案The
Model.save
method accepts theusing
parameter to specify the database:foo = Foo(fields) foo.save(using='staging')
The
ModelForm.save
method returns theModel
instance:foo_form = FooImportForm(fields) foo = foo_form.save()
The
ModelForm.save
method can optionally be told not to commit:foo_form.save(commit=False)
Putting it all together:
foo_form = FooImportForm(fields) foo = foo_form.save(commit=False) foo.save(using='staging')
这篇关于使用具有ModelForm的特定数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!