Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

factory boy - how to generate a subfactory based on condition of a parent attribute

I have a factory like so:

class PayInFactory(factory.DjangoModelFactory):
    class Meta:
        model = PayIn
  
    @factory.lazy_attribute
    def card(self):
        if self.booking_payment and self.booking_payment.payment_type in [bkg_cts.PAYMENT_CARD, bkg_cts.PAYMENT_CARD_2X]:
            factory.SubFactory(
                CardFactory,
                user=self.user,
            )

I'm trying to generate a field card only if the booking_payment field has a payment_type value in [bkg_cts.PAYMENT_CARD, bkg_cts.PAYMENT_CARD_2X]

The code goes into that statement but card field is empty after generation.

How can I do that properly ? Is SubFactory allowed in lazy_attribute ?

I'd like to be able to modify Card field from PayInFactory if possible like so:

>>> PayInFactory(card__user=some_user)

PostGeneration won't do as I need this Card to be available before the call to create. I overrided _create and it may use the card if available.

Thanks !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution lies in factory.Maybe:

class PayInFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.PayIn

    card = factory.Maybe(
        factory.LazyAttribute(
            lambda o: o.booking_payment and o.booking_payment.payment_type in ...
        ),
        factory.SubFactory(
            CardFactory,
            # Fetch 'user' one level up from CardFactory: PayInFactory
            user=factory.SelfAttribute('..user'),
        ),
    )

However, I haven't tested whether the extra params get actually passed to the CardFactory, nor what happens when CardFactory is not called — you'll have to check (and maybe open an issue on the project if you get an unexpected behaviour!).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...