我有很多Hardware
模型有一个HardwareType
具有各种特征。就像这样:
# 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 [...]
如果我想添加一个新的Hardware
对象,我首先必须检索HardwareType
每次,这不是很干:
tmp_hd_type = HardwareType.objects.get(name='NG35001')
new_hd = Hardware.objects.create(type=tmp_hd_type, is_installed=True, ...)
因此,我尝试重写HardwareManager.create()
创建新类型时自动导入类型的方法Hardware
像这样:
# 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, ...)
但我不断收到来自 ORM 的错误和非常奇怪的行为(我这里没有,但如果需要的话我可以发布它们)。我在 Django 文档和 SO 线程中进行了搜索,但大多数情况下我最终得到的解决方案是:
- the
Hardware.save()
方法被重写(我应该得到HardwareType
在那里?)或者,
- 经理定义了一个新的
create_something
调用的方法self.create()
.
我也开始深入研究代码并发现Manager
是某种特殊的QuerySet
但我不知道如何从那里继续。我真的很想更换create
方法到位,我似乎无法管理这个。是什么阻止我做我想做的事?