Get id of FactoryBoy factory with LazyAttribute when using DjangoModelFactory


I have the following factory and want to access the id of an instance that will be created from it:

class PlatformFactory(factory.django.DjangoModelFactory):
    type = factory.fuzzy.FuzzyChoice(Platform.Type)
    name = factory.fuzzy.FuzzyText(length=30)
    user = factory.SubFactory(UserFactory)
    ext = factory.LazyAttribute(lambda self: f"{self.user.key}|{}")

    class Meta:
        model = Platform
        exclude = ["user", ]

Unfortunately it gives me the error AttributeError: The parameter 'id' is unknown. Evaluated attributes are {'type': <Type.OTHER: 2>, 'name': ...

But since it is a django model there is an id present. Why is this not recognized by factory boy and how can I solve this?

Thanks and regards


Based on the docs on LazyAttribute, the method accepts the object being built, which I think the object is not created/saved yet that is why there’s no id yet. (Correct me if I’m wrong)

In any case, you should be able to achieve what you want using PostGeneration

class PlatformFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Platform
        exclude = ["user", ]

    def set_ext(obj, create, extracted, **kwargs):
        if not create:
        obj.ext = f"{obj.user.key}|{}"

Answered By – Rieljun Liguid

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published