Django 自定义命令不创建新条目

问题描述 投票:0回答:1

我是 Django 的新手,我正在开发一个简单的应用程序,每天为位置列表生成 json 预测数据。然后使用此数据向用户显示预测。我设置了一个 startjobs.py 来运行一些生成我的应用程序所需的 json 数据的函数。

我遇到了作业成功运行的问题,但是,没有添加新条目,也没有创建新的 json 文件。我查看了一些类似的问题,但找不到适合我的案例的解决方案。

这是我的模型:

class Location(models.Model):
    location = models.CharField(max_length = 75, unique = True)

    def __str__(self):
        return f"{self.location}"


INTERVAL_CHOICES = [
    ('today', 'Today'),
    ('hourly', 'Hourly'),
    ('daily', 'Daily'),
]

class Forecast(models.Model):
    location =  models.ForeignKey(Location, on_delete = models.CASCADE)
    date = models.DateField()
    interval = models.CharField(max_length = 6, choices = INTERVAL_CHOICES, default = 'today')
    filename = models.FileField(upload_to = 'test/')

    def __str__(self):
        return f"Forecast for max wave height - {self.interval} in {self.location} on {self.date}"

还有我的 startjobs.py(我的工作每 2 分钟运行一次以进行测试):

locations = Location.objects.values_list("location", flat=True)

def save_new_forecasts():

    date = dt.date.today().strftime("%Y-%m-%d")

    for location in locations:
        if not Forecast.objects.filter(date = date).exists:
            daily_data = create_daily_forecast(location)
            hourly_data = create_hourly_forecast(location)
            daily_forecast = Forecast(
                location = location,
                date = date,
                interval = daily_data[0],
                filename = daily_data[1]
            )
            daily_forecast.save()
            hourly_forecast = Forecast(
                location_id = location,
                date = date,
                interval = hourly_data[0],
                filename = hourly_data[1]
            )
            hourly_forecast.save()

def create_daily_forecast(location):

    interval = "daily"
    filename = fg_daily.generate_daily_forecast(location, 10)

    return [interval, filename]

def create_hourly_forecast(location):
   
    location_id = location
    date = dt.date.today().strftime("%Y.%m.%d")
    interval = "hourly"
    filename = fg_hourly.generate_hourly_forecast(location, 24)

    return [location_id, date, interval, filename]

def delete_old_job_executions(max_age=604_800):
    DjangoJobExecution.objects.delete_old_job_executions(max_age)

class Command(BaseCommand):
    help = "Runs apscheduler."

    def handle(self, *args, **options):
        scheduler = BlockingScheduler(timezone=settings.TIME_ZONE)
        scheduler.add_jobstore(DjangoJobStore(), "default")

        scheduler.add_job(
            save_new_forecasts,
            trigger="interval",
            minutes=2,
            id="Forecasts",
            max_instances=1,
            replace_existing=True,
        )
        logger.info("Added job: Save New Forecasts")

        scheduler.add_job(
            delete_old_job_executions,
            trigger=CronTrigger(
                day_of_week="mon", hour="00", minute="00"
            ),  # Midnight on Monday, before start of the next work week.
            id="Delete Old Job Executions",
            max_instances=1,
            replace_existing=True,
        )
        logger.info("Added weekly job: Delete Old Job Executions.")

        try:
            logger.info("Starting scheduler...")
            scheduler.start()
        except KeyboardInterrupt:
            logger.info("Stopping scheduler...")
            scheduler.shutdown()
            logger.info("Scheduler shut down successfully!")

编辑:

我认为查看一些创建 json 的函数也可能有帮助:

def generate_json(location, interval, data):
    df = pandas.DataFrame(data=data)
    filename = generate_filename(location, interval)
    df.to_json(f'{PATH}/{filename}', orient='records')
    return filename
def generate_daily_forecast(location, length):
    date_list = generate_date_list(length)
    height_list = generate_height_list(length)
    keys = ["date", "max_wave_height"]
    values = ['', '']
    data = []

    for dates in date_list:
        i = date_list.index(dates)
        values[0] = date_list[i]
        values[1] = height_list[i]
        pre_data = dict(zip(keys, values))
        data.append(pre_data)

    filename = generate_json(location, 'daily', data)
    return filename

任何帮助将不胜感激!谢谢!

python django django-models jobs apscheduler
1个回答
0
投票

需要在if语句中过滤日期和地点:

def save_new_forecasts():

    date = dt.date.today().strftime("%Y-%m-%d")

    for location in locations:
        if not Forecast.objects.filter(date = date).exists:

© www.soinside.com 2019 - 2024. All rights reserved.