我有很多Hardware
模型,其中有HardwareType
各種特徵。像這樣:如何重寫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 [...]
如果我想添加一個新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線程,但主要是我結束了在哪裏解決方案:(?我應該得到的HardwareType
那裏)
- 的
Hardware.save()
方法被覆蓋或 - 經理定義一種新的
create_something
方法,其調用self.create()
。
我也開始挖掘到代碼中,只見那Manager
是一些特殊的QuerySet
但我不知道如何從那裏繼續。我真的想替換create
方法,我似乎無法處理這一點。什麼阻止我做我想做的事情?
我會在幾個小時試試這個,並與錯誤(如果有的話)送還給你。謝謝 ! – achedeuzot
2。x您可以使用'isinstance(foo,basestring)'來捕獲Unicode和str。 –
@DanielRoseman是否使用模型中定義的'model.save'方法或''Manager.create'? – DhiaTN