如何将起始序列号传递给Django factory_boy工厂?
作者:互联网
factory_boy默认为1表示序列.如何传入一个数字作为不同的起始号码呢?我可以继承_setup_next_sequence()方法,但是如何给它一个变量来使用呢?
# File: models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
# File: factories.py
from .models import Book
import factory
class BookFactory(factory.Factory):
FACTORY_FOR = BookModel
title = factory.Sequence(lambda n: u'Title #{}'.format(n))
@classmethod
def _setup_next_sequence(cls):
# Instead of defaulting to starting with number 1, start with starting_seq_num.
# But how do I set starting_seq_num?
return starting_seq_num
# File: make_data.py
from factories import BookFactory
# somehow set starting sequence number here?
BookFactory().create()
我正在使用factory_boy 1.2.0(通过pip install factory_boy)
factory_boy代码:https://github.com/dnerdy/factory_boy
解决方法:
除了Rob Bednark的答案
我们可以使用reset_sequence()
功能,它将计数器重置为特定值.
# File: make_data.py
import factories
factories.BookFactory.reset_sequence(100)
my_book = factories.BookFactory().create()
print(my_book.title) # Title #100
标签:python,class-method,django,factory-boy 来源: https://codeday.me/bug/20190529/1179191.html