gpt4 book ai didi

python - 如何将起始序列号传递给 Django factory_boy 工厂?

转载 作者:太空狗 更新时间:2023-10-30 00:51:04 24 4
gpt4 key购买 nike

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 - 如何将起始序列号传递给 Django factory_boy 工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15402256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com