Hardware
のモデルは、さまざまな特性を持つHardwareType
を持っています。私は新しいHardware
オブジェクトを追加したい場合はDjangoでmodel.Manager.create()メソッドをオーバーライドする方法は?
# models.py
from django.db import models
class HardwareType(model.Models):
name = models.CharField(max_length=32, unique=True)
# some characteristics of this particular piece of hardware
weight = models.DecimalField(max_digits=12, decimal_places=3)
# and more [...]
class Hardware(models.Model):
type = models.ForeignKey(HardwareType)
# some attributes
is_installed = models.BooleanField()
location_installed = models.TextField()
# and more [...]
、私が最初にHardwareType
に非常に乾燥していないすべての時間を取得する必要があります:そのような
tmp_hd_type = HardwareType.objects.get(name='NG35001')
new_hd = Hardware.objects.create(type=tmp_hd_type, is_installed=True, ...)
したがって、私はオーバーライドに試してみました
# models.py
from django.db import models
class HardwareType(model.Models):
name = models.CharField(max_length=32, unique=True)
# some characteristics of this particular piece of hardware
weight = models.DecimalField(max_digits=12, decimal_places=3)
# and more [...]
class HardwareManager(models.Manager):
def create(self, *args, **kwargs):
if 'type' in kwargs and kwargs['type'] is str:
kwargs['type'] = HardwareType.objects.get(name=kwargs['type'])
super(HardwareManager, self).create(*args, **kwargs)
class Hardware(models.Model):
objects = HardwareManager()
type = models.ForeignKey(HardwareType)
# some attributes
is_installed = models.BooleanField()
location_installed = models.TextField()
# and more [...]
# so then I should be able to do:
new_hd = Hardware.objects.create(type='ND35001', is_installed=True, ...)
しかし、私はsの本当にエラーを得続けると:新しいHardware
を作成するときに、自動的にそのようにタイプをインポートする方法HardwareManager.create()
ORMからの変則的な振る舞い(私はここにそれらを持っていませんが、必要ならば投稿することができます)。 、
Hardware.save()
メソッドがオーバーライドされるか:私は、DjangoのドキュメントとSOのスレッドで検索したが、ほとんど私は解決策に終わる(私はそこにHardwareType
を取得する必要があります?)self.create()
を呼び出す新しいcreate_something
メソッド。
私はまた、コードに掘り始め、Manager
がQuerySet
のいくつかの特別な種類であることを見ましたが、私はそこから継続するのか分かりません。私は実際にcreate
メソッドを置き換えたいと思います。私はこれを管理できないようです。私がやりたいことをやり遂げるのを妨げているのは何ですか?
私は時間のカップルでこれを試すとエラー(もしあれば)をあなたに戻って取得します。ありがとう! – achedeuzot
In。xでは、isinstance(foo、basestring)を使ってunicodeとstrの両方を捕捉することができます。 –
@DanielRosemanは、 'Manager.create'をモデルで定義された' model.save'メソッドを使用するかどうかを行いますか? – DhiaTN