pythad pythad - 1 year ago 31
Python Question

The best model design to save function call into db

I have some sort of a

Task
s in my project. Task and its parameters later will be constructed into a function call.

Now my
Task
model looks like:

class Task(TimeStampedModel):
ACTIVE = 1
COMPLETED = 0
FAILED = -1
STATUS_CHOICES = (
(ACTIVE, 'Active'),
(COMPLETED, 'Completed'),
(FAILED, 'Failed'),
)
ACTION1 = 1
ACTION2 = 2
ACTION3 = 3
ACTION_CHOICES = (
(ACTION1, 'Action1'),
(ACTION2, 'Action2'),
(ACTION3, 'Action3'),
)
status = models.SmallIntegerField(choices=STATUS_CHOICES, default=ACTIVE)
action = models.SmallIntegerField(choices=ACTION_CHOICES, default=ACTION1)
date_completed = models.DateTimeField(null=True, blank=True)


Later I will create
Task
object and depending on its
action
call a particular function. For example, if
task.action == 1
I will call
some_module.action1()
. I am curious on how I can store arguments that can be passed to a function (
some_module.action1(arg1, arg2)
) if I am not sure what they will be in the future. So, if it is possible to say so, I want store some sort of a dictionary on function kwargs as my field. What's the best way to archive what I want?

Answer Source

You can use JSON field. if you use Postgres, it has built in JSON field support, otherwise you can install(or write by your own ) a library to make pseudo JSON field: https://pypi.python.org/pypi/django-jsonfield https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#jsonfield

I use django-jsonfield in a few projects and it works smoothly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download