简体   繁体   中英

Django 1.11 How to execute a code only once that save a data to DB using Django model

I am geting started with Django Rest Framework, my app is based on Django 1.11 version.

I have a model name Test. Now I need to populate this model once only when the app starts up, which will recieve a data from a REST API call. I read about app.ready() however I coudn't figure out how to wire up these steps.

So basically when the app starts up :

  1. Check if there is some data present in the table A, preferably by calling objects.count().

  2. If yes do nothing.

  3. If not, call the third party API and save the model.

This can also be done on Admin?

There are several ways of doing that. Most cleaner approach is to create a new custom command like this:

# app/management/commands/updateappdb.py

from django.core.management.base import BaseCommand, CommandError   
from polls.models import Question as Poll

class Command(BaseCommand):
    help = 'Update DB'


    def handle(self, *args, **options):
        # Update code here
        if not YourModel.objects.exists():
           # do something
        self.stdout.write(self.style.SUCCESS('Successfully Updated')

Then you can use this command for example:

python manage.py updateappdb && python manager.py runserver

There is another approach, which is to write these in urls.py . Urls.py load once whenever the server starts. So in urls.py you can try like this:

from django.confs.urls.defaults import *
from your_file import data_import_function  # which has the data load functionality

urlpatterns = [...]

data_import_function()

But among these two approaches, I prefer the first one. Because it will more reusable and you can integrate this custom command with cronjob if you want periodic updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM