1

Basically, I want to store python modules with a few simple functions in my database. My project runs on Django. I came across python_field, however, its buggy. I want to execute the code on the save method for the Model. What is the standard way to do this? Thanks.

2
  • 1
    I think there's a larger question here. Why do you want to save code in a database? Commented Aug 26, 2017 at 14:05
  • 1
    I can't judge ... since they are people writing javascript on server side. Commented Aug 26, 2017 at 14:22

1 Answer 1

1

I guess they are not a standard way to do it because it looks like an antipattern. Anyway, for academical purposes, you can try with:

from django.db import models
from python_field.fields import PythonCodeField

class MyModel(models.Model):
    ....
    source = PythonCodeField(blank=True, null=True)

    ....

    def save(self, *args, **kwargs):
        codeObject = compile(self.source, '<string>', 'exec')
        exec( codeObject )  #executing before regular save
        super(MyModel, self).save(*args, **kwargs)
        exec( codeObject )  #executing after regular save
Sign up to request clarification or add additional context in comments.

4 Comments

OP already said python_field's buggy so any other alternative would be good rather than this one
@ArpitSolanki, just focused on question. I also included disclaimer. OP ask to execute it on save method, here it is ... with a big disclaimer. OP don't ask for alternative method. You agree?
I don't agree why he want to store the code in DB itself but answer is okay itself.
Nice! my answer is about how to do it, I do not judge whether that is good or bad. I disclaimed that for me looks like bad, but I don't know all the whole context :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.