Reputation: 64793
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
Upvotes: 1
Views: 171
Reputation: 6353
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.
Upvotes: 2
Reputation: 599480
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.
Upvotes: 5