如何单独操作Django-ORM模型?

时间:2019-03-14 10:25:18

标签: python django django-orm

我的目录结构如下:

├─bin
├─conf
│  └─django_settings.py
├─docs
├─log
└─src
   └─main.py
   └─models.py

在我的main.py中,我想使用django-orm从我的MySQL表campaign_plan中读取数据,但是当我尝试运行main.py时,出现此错误:< / p>

  

django.core.exceptions.AppRegistryNotReady:应用尚未加载。

如何成功获取正确的数据?

models.py

from django.db import models

class CampaignPlan(models.Model):
    campaign_id = models.CharField(max_length=64, blank=True, null=True)
    rule_id = models.IntegerField(blank=True, null=True)
    status = models.IntegerField(blank=True, null=True)
    account_id = models.CharField(max_length=64, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'campaign_plan'
        unique_together = (('campaign_id', 'rule_id', 'status'),)

main.py

import sys, os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.join(BASE_DIR,'conf'))
sys.path.append(os.path.join(BASE_DIR, "src"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_settings")

from models import CampaignPlan


class AutoManagementService(object):

    def __init__(self, campaign_plan):
        self.campaign_plan = campaign_plan

    def run(self):
        pass

campaign_plans = CampaignPlan.objects.all()

1 个答案:

答案 0 :(得分:2)

您需要设置Django:

import django

django.setup()