Search code examples
djangounit-testingtestingfactory-boy

Is it possible to get the value of a Factory boy Faker object for use in another field while making a DjangoModelFactory


I am trying to use factory boy to create a model instance for events, but I am needing to see if I can access the result of a Faker declaration in another field. In the code below, I want to access the start_time field in the end_time field so I can create a datetime that is 1 hour from the start_time. It complains that start_time is a faker object, and not a datetime object. How do I get the Faker class to render its information so I can use it in the end_time field?

class EventFactory(DjangoModelFactory):
    class Meta:
        model = Event

    client = factory.SubFactory(
        ClientFactory,
    )
    customer = factory.SubFactory(
        CustomerFactory,
    )
    resource = factory.SubFactory(
        ResourceFactory,
    )
    title = Faker("sentence", nb_words=5)
    start_time = Faker(
        "date_time_between_dates",
        datetime_start=datetime.datetime.now(),
        datetime_end=datetime.datetime.now() + datetime.timedelta(days=30),
    )
    end_time = start_time + datetime.timedelta(hours=1)
    all_day = False
    background_color = None
    border_color = None
    text_color = None
    duration = datetime.timedelta(hours=1)

Solution

  • LazyAttribute gives you a way to access other attributes within the object you are creating. Try to define your end_time like so:

        end_time = factory.LazyAttribute(
            lambda o: o.start_time + datetime.timedelta(hours=1)
        )