Handling GenericForeignKey's
Opened this issue · 3 comments
def get_generator(self, field):
if field.name == 'content_type':
return generators.ChoicesGenerator(
values=[ContentType.objects.get_for_model(m)
for m in [ModelOne, ModelTwo, ModelThree]])
elif field.name == 'object_id':
# where to pick right model class? ¯\(°_o)/¯
I think, for that case, instances of GeneridForeignKey
are also could be passed to get_generator()
, and being skipped in base implementation, so user will can handle them in subclass method.
Or another hook like prost_process_instance
could be defined, which must be called before instance being saved first time.
Another issue with GFK's is that you cant just do autofixture.creante_one(SomethingWithGFK, field_values={'content_object': some_object})
content_type
will be set to random ContentType
and object_id
to random value, so content_object
will refer to unexistent object.
I took a crack at implementing this.
Added generator for GenericFK relations.
Overall method: find GenericFK fields from model._meta.virtual_fields,
add them to the list of fields to be processed, and remove the
constituent content_type and object_id fields from the processing list.
Then use the GenericFK generator to either select or create an
object to assign.
Here is how I'm using AutoFixture in models with GenericForeignKey.
Feel free to use and/or modify it.
https://gist.github.com/alb3rto269/def529c94f47272bed8d2990c93d99f2