覆盖 _create 类方法
Overriding _create classmethod
我正在使用 django 并且有一个自定义方法来创建特定模型的新对象:
class DiseaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Disease
def _create(cls, model_class, *args, **kwargs):
obj = model_class.create_new(first_name=f"Disease{uuid.uuid4()}")
return obj
当我尝试使用 DiseaseFactory.create() 创建 DiseaseFactory 实例时,它抛出错误:
TypeError: _create() missing 1 required positional argument:
'model_class'
我做错了什么?
为了让它工作,你需要像这样添加@classmethod装饰器:
class DiseaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Disease
@classmethod
def _create(cls, model_class, *args, **kwargs):
obj = model_class.create_new(first_name=f"Disease{uuid.uuid4()}")
return obj
我正在使用 django 并且有一个自定义方法来创建特定模型的新对象:
class DiseaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Disease
def _create(cls, model_class, *args, **kwargs):
obj = model_class.create_new(first_name=f"Disease{uuid.uuid4()}")
return obj
当我尝试使用 DiseaseFactory.create() 创建 DiseaseFactory 实例时,它抛出错误:
TypeError: _create() missing 1 required positional argument: 'model_class'
我做错了什么?
为了让它工作,你需要像这样添加@classmethod装饰器:
class DiseaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Disease
@classmethod
def _create(cls, model_class, *args, **kwargs):
obj = model_class.create_new(first_name=f"Disease{uuid.uuid4()}")
return obj