django-autofixture icon indicating copy to clipboard operation
django-autofixture copied to clipboard

Handling GenericForeignKey's

Open AndreiPashkin opened this issue 11 years ago • 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.

AndreiPashkin avatar Feb 02 '14 21:02 AndreiPashkin

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.

AndreiPashkin avatar Feb 13 '14 11:02 AndreiPashkin

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.

aschriner avatar Apr 07 '14 13:04 aschriner

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

alb3rto269 avatar Mar 23 '18 20:03 alb3rto269