使用具有ModelForm的特定数据库 [英] Use a specific database with a ModelForm

查看:114
本文介绍了使用具有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)
foo = foo_form.save()
pre>

可以选择不要提交 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 the staging database when I form.save()? I can't see a place where to specify the equivalent of using('staging').

解决方案

The Model.save method accepts the using parameter to specify the database:

foo = Foo(fields)
foo.save(using='staging')

The ModelForm.save method returns the Model 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屋!

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