如何创建一个自动生成所有字段的factory\u boy工厂?

2024-09-29 23:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将Django代码从milkman迁移到factory_boy。在

假设我有一个模型:

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    number = models.IntegerField()

我写了一个工厂:

^{pr2}$

但是,默认情况下,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.']}

但是,送奶工可以自动为这些字段生成值:

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创建工厂,以便所有字段都自动填充合法值?在


Tags: innumberfieldtitlemodelsfactory工厂be

热门问题