Execute code based on selection

Dear all,
I’m stugging with a simple design decision and would appritiat if someone could push me into the right direction.
What I’m trying to achive:
A user should be able to upload data related to a project and parse it using a project specific parser.
The parser more or less reads ini files and returns json but I need different version of the parser for different versions of the data uploaded.
I’m not sure how to make the connection between the different implementations of the parsers and the entries in the Parser Model.

Hope my problem is understandable somehow.

class Parser(models.Model):
    version = models.CharField(max_length=32, ...)

class Project(models.Model):
    parser = models.ForeignKey(Parser, on_delete=CASCADE, default=None)

class ProjectData(models.Model):
    project = models.ForeignKey(Project, on_delete=CASCADE, default=None)
    data = models.TextField()

Does it make sense at all to have the table Parser in the DB and fixed implementations of the parser?

Thanks, Tomasz.

Yes, and yes. :slightly_smiling_face:

Are the implementations of the parsers functions, or are they classes, or are they external modules?

Let’s take the simple case - you have functions in a class named Parsers named parser_x and parser_y. They’re class methods so you don’t need an instance of Parsers. If you have a variable use_parser = 'parser_x', you can then call that method using the getattr function as result = getattr(Parsers, use_parser)(parameters)

Side note: We do something very similar to this for our permission system. It’s a technique that works really well for us.

Thanks for the quick and helpfull response.

The parsers are not implemented yet and I can choose the implementation. I will probably go for a class or follow your example.

It looks like I’m not only lacking django skills but also python :grinning: (I’m new to both).