polyfactory icon indicating copy to clipboard operation
polyfactory copied to clipboard

Allow partial attributes factory for child factories (randomly generating only missing fields for child models)

Open phbernardes opened this issue 2 years ago • 4 comments

Given the following Pydantic models and Factory:

from pydantic_factories import ModelFactory
from pydantic import BaseModel


class Pet(BaseModel):
    name: str
    age: int


class Person(BaseModel):
    name: str
    pets: list[Pet]
    age: int


class PersonFactory(ModelFactory[Person]):
    __model__ = Person

When trying to build:

data = {
    'name': 'John',
    'pets': [
        {'name': 'dog'},
        {'name': 'cat'},
    ],
}

PersonFactory.build(**data)

Then the following exception is raised:

ValidationError: 2 validation errors for Person
pets -> 0 -> age
  field required (type=value_error.missing)
pets -> 1 -> age
  field required (type=value_error.missing)

We see that the age is missing in the data, so the factory is not able to construct the model.

If we add the age to the data:

data = {
    'name': 'John',
    'pets': [
        {'name': 'dog', 'age': 3},
        {'name': 'cat', 'age': 4},
    ],
}

PersonFactory.build(**data)

The factory will construct the model instance:

Person(name='John', pets=[Pet(name='dog', age=3), Pet(name='cat', age=4)], age=5978)

Note: only the age of the Pets (child model) is necessary, ModelFactory handles to randomly fill the age of Person.

It would be great to have the same behaviour of Factory Boy. If we pass only part of the attributes of a child model, then the factory will generate the missing attributes for us.

Can we work on this feature?

phbernardes avatar Jul 25 '22 13:07 phbernardes

Sure, go ahead

Goldziher avatar Jul 25 '22 13:07 Goldziher

Great, I'll work on a PR.

pedro-prose avatar Jul 25 '22 14:07 pedro-prose

any updates? @pedro-prose

Goldziher avatar Aug 02 '22 09:08 Goldziher

Hi, I didn't had the time this last week. I'll work on it this week.

phbernardes avatar Aug 02 '22 18:08 phbernardes

released

Goldziher avatar Aug 09 '22 12:08 Goldziher

released

Thank you!

phbernardes avatar Aug 09 '22 12:08 phbernardes