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}|{self.id}")
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 Matt
CodePudding user response:
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", ]
@factory.post_generation
def set_ext(obj, create, extracted, **kwargs):
if not create:
return
obj.ext = f"{obj.user.key}|{obj.id}"
obj.save()