views:

100

answers:

2

Hello, I want to execute a random .py file, say foo.py on the myproject/myapp folder by using crobjob by some periods

I have this basic model in my model.py for the app:

class Mymodel(models.Model):
    content = models.TextField()

Say I have this in my foo.py, I want to check if there is any Mymodel object that has a content field as same as mytext, if not make a new Mymodel with the mytext as content, if already existing do nothing.

<do django importings>
mytext = "something here"
if Mymodel.filter(content=mytext) == null:
    newitem = Mymodel(content=mytext)
    newitem.save()
else:
    pass

So here is my question, what django imports shall I be doing? Also how can I check if the query has no item (don't know if if Mymodel.filter(content=mytext) == null would work. Also I don't know if this is an efficient way to achieve my goal as the amount of Mymodel will be high.

Thanks

+5  A: 

You have two separate questions here - it would have been better to split them out.

To run a separate script, you're best off creating a ./manage.py command. See the documentation on how to do this.

For your second question, the code you give is not valid Python, since there is no 'null' value - you mean None. However even then the code will not work, as that isn't how you write that query using the Django ORM. You want something like this:

if not MyModel.objects.filter(content=mytext).count():

which asks the database how many items there are with content=mytext, and is True if there are none.

Daniel Roseman
thabjs alot daniel for the answer, do I need to import django and models while doing custom commands? The documentation lacks the detailed information
Hellnar
You always need to import your models if you're using them in your script, and whatever Django modules you're using. This is true of any Python code.
Daniel Roseman
+2  A: 

You might also check out django-extensions, which has a built-in manage.py extension called "runscript" that executes any python script in your django project's context.

Prairiedogg