我正在尝试从 milkman 迁移 Django 代码至 factory_boy .
假设我有一个模型:
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
number = models.IntegerField()
我写了一个工厂:
import factory
class BlogPostFactory(factory.Factory):
class Meta:
model = BlogPost
但是,factory_boy 默认为这些字段生成无效值:
In [17]: bp = BlogPostFactory.build()
In [18]: print "title: %r content: %r number: %r" % (bp.title, bp.content, bp.number)
title: u'' content: u'' number: None
In [19]: bp.full_clean()
ValidationError: {'content': [u'This field cannot be blank.'], 'number': [u'This field cannot be null.'], 'title': [u'This field cannot be blank.']}
但是,milkman 可以自动为这些字段生成值:
In [22]: bp = milkman.deliver(BlogPost)
In [23]: print "title: %r content: %r number: %r" % (bp.title, bp.content, bp.number)
title: 'A8pLAni9xSTY93QJzSi5yY8SGQikL7YGrcTZVViAFS72eqG2bLWHSh0lNLSA2FbH7kSCXDktCQxUO288HTXdYUcRNUikoH4LQ4QHmy6XRwrRzbbmwXL6pLW7tapJM3FTpx8oBbTUw7nCOZew73xjWsID666FKh05ychptiF2peEZHdQd6gnHqXtFkL5kyEIhFvinOCmS' content: 'RUcSHCxs' number: -709949545
我知道 factory_boy 提供了 fuzzy attributes , 但你必须明确使用它们或 use tons of model/field reflection .
是否可以使用 factory_boy 创建一个工厂,以便所有字段都自动填充合法值?
最佳答案
关于python - 如何创建一个自动生成所有字段的 factory_boy 工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600170/