从数据库导入数据导入不起作用

时间:2016-11-10 13:44:51

标签: python django django-models django-admin

我正在尝试设置一个脚本,该脚本将运行每半个左右的房子,以便将作业分成优先级。

#from jobs.models import Jobs
#from django.db import models
#from jobs.states import RepairStates
# Get jobs
# Get models
# Get states

Job_set = Jobs.objects.filter(status="invoiced")
for jobs in Job_set:
    print(jobs.status)

print("Hello")

# Loop through all jobs that do not have a status of "invoiced"
# Calculate how many days until Due date / How many days past due date
# Check what state the job is in and add or take away points depending on state
# return points

# Quote Accepted = - 2
# Assigned engineer = -1
# request components = 0
# order fulfilled = 1
# test + 2
# Completed + 3
# for dispatch + 4
# COMPLETED + 100

#Do this every half hour, hour.

我已经陷入了第一道障碍,我似乎无法导入表格数据,我需要尝试多次使用不同的位置,但它似乎不起作用。

我的目录是这样的

 twm--
      other files(not important)
      twm--
           accounts
           api
           component
           customer
           engineering
           goods
           jobs 
           personal 
         so on....

现在模型在jobs.models中,但我已经尝试过了,

from jobs.models import Jobs 

但它吐出了一个错误告诉我

     C:\Users\Staff\Documents\tsl\twm\twm>python priorityalgorithm.py
  Traceback (most recent call last):
   File "priorityalgorithm.py", line 1, in <module>
    from jobs.models import Jobs
  File "C:\Users\Staff\Documents\tsl\twm\twm\jobs\models.py", line 4, in     <module>
    from django.db import models
   File "C:\Python34\lib\site-packages\django\db\models\__init__.py", line 6, in <module>
    from django.db.models.query import Q, QuerySet, Prefetch  # NOQA
   File "C:\Python34\lib\site-packages\django\db\models\query.py", line 16, in <module>
     from django.db.models import sql
   File "C:\Python34\lib\site-packages\django\db\models\sql\__init__.py", line 2, in <module>
     from django.db.models.sql.subqueries import *  # NOQA
   file "C:\Python34\lib\site-packages\django\db\models\sql\subqueries.py", line 9, in <module>
    from django.db.models.sql.query import Query
   File "C:\Python34\lib\site-packages\django\db\models\sql\query.py", line 17, in <module>
     from django.db.models.aggregates import Count
   File "C:\Python34\lib\site-packages\django\db\models\aggregates.py", line 5, in <module>
     from django.db.models.expressions import Func, Star
  File "C:\Python34\lib\site-packages\django\db\models\expressions.py", line 7, in <module>
    from django.db.models import fields
  File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line 19, in <module>
    from django import forms
   File "C:\Python34\lib\site-packages\django\forms\__init__.py", line 6, in <module>
    from django.forms.fields import *  # NOQA
  File "C:\Python34\lib\site-packages\django\forms\fields.py", line 21, in <module>
    from django.forms.utils import from_current_timezone, to_current_timezone
   File "C:\Python34\lib\site-packages\django\forms\utils.py", line 12, in <module>
    from django.utils.html import escape, format_html, format_html_join, html_safe
  File "C:\Python34\lib\site-packages\django\utils\html.py", line 13, in <module>
    from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS
  File "C:\Python34\lib\site-packages\django\utils\http.py", line 10, in <module>
    from email.utils import formatdate
  File "C:\Users\Staff\Documents\tsl\twm\twm\email.py", line 1, in <module>
    from django.core.mail import EmailMultiAlternatives
  File "C:\Python34\lib\site-packages\django\core\mail\__init__.py", line 14, in <module>
    from django.core.mail.message import (
  File "C:\Python34\lib\site-packages\django\core\mail\message.py", line 8, in <module>
from email import (
ImportError: cannot import name 'charset'

有谁知道为什么会这样?

按要求编写jobs.models 编辑 - 我正在处理的文件位于作业模块旁边的twm应用程序中

from decimal import Decimal
from datetime import datetime, timedelta

from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist

from statemachine.fields import FSM_StateField
from twm.component.models import Manufacturer
from twm.engineering.models import RefurbKit
from twm.workitem.models import WorkItem, WorkItemNote, WorkItemEmail
from twm.jobs.states import RepairStates
from twm.procurement.models import PurchaseOrderLine
from twm.engineering.models import ComponentLine
from twm.customer.models import ContactEmail

class Job(WorkItem):
    REFERENCE_START = 30000
    SLA_CHOICES = (('Standard', 'Standard'), ('Next day', 'Next day'),)
    SLA = models.CharField(max_length=20,
                           default='Standard', choices=SLA_CHOICES)
    part = models.ForeignKey("jobs.Part", null=True, blank=True)
    serial_no = models.CharField(max_length=50)
    status = FSM_StateField(machine=RepairStates, default_choices_all=True)
    quote_expiry = models.DateTimeField(null=True, blank=True)
    warranty = models.BooleanField(default=False)
    PriorityPoints = models.IntegerField(default=0, null=False)
    #    contact_emails = models.ManyToManyField('customer.ContactEmail')

    ident = "Repairs"

    def __unicode__(self):
        return "%s - %s" % (self.ref_number, self.customer)

    def add_note(self, user, note):
        return JobNote(user=user, note=note, item=self)

    def add_email(self, emails, subject, message, mime_type="text/html"):
        return JobEmail(item=self,
                        sent_to=emails,
                        subject=subject,
                        note=message,
                        upload_MIME=mime_type)

    def add_customer_as_contact(self):
        if self.customer and self.customer.addresses.count() > 0:
            address = self.customer.addresses.all()[0]
            contact, created = ContactEmail.objects.get_or_create(customer=self.customer,
                                                                  email=address.email,
                                                                  defaults={'name': address.contact_name})
            self.contact_emails.add(contact)

    def set_due_date(self):
        if self.status.state.name == "goods_arrived":
            deadlines = (1, 4)
        else:
            deadlines = (1, 6)

        if self.SLA == 'Next day':
            due_date = datetime.now() + timedelta(days=deadlines[0])
        else:
            due_date = datetime.now() + timedelta(days=deadlines[1])

            #can't be due on a weekend! (5=Saturday, 6=Sunday)
            add_days = 7 - due_date.weekday()
            if add_days < 3:
                due_date += timedelta(days=add_days)

        self.due_date = due_date

    def set_quote_expiry(self):
        self.quote_expiry = datetime.now() + timedelta(days=30)

    def get_notes(self):
        return self.notes.all()

    def get_open_quote(self):
        quotes = self.quote.filter(models.Q(accepted__isnull=True) |
                                   models.Q(accepted__gt=-1)).order_by('-date')
        if quotes:
            return quotes[0]

    def get_accepted_quote(self):
        quotes = self.quote.filter(accepted__gt=0).order_by('-date')
        if quotes:
            return quotes[0]

    def get_qa_state(self):
        last_qa_state = self.state_history.filter(from_state='production_qa')
        if last_qa_state:
            return last_qa_state[0]

    def update_value(self, save=True):
        value = Decimal(0)
        quotes = self.quote.filter(accepted__gt=0).order_by('-date')
        if quotes.count() == 0:
            quotes = self.quote.all().order_by('-date')
            if quotes.count() > 0:
                quote = quotes[0]
                value += quote.new_price or 0
                value += quote.used_price or 0
                value += quote.repair_price or 0
                value += quote.exchange_price or 0
                value += quote.other_price or 0
                value += quote.inbound_shipping_cost or 0
                value += quote.outbound_shipping_cost or 0
        else:
            for quote in quotes:
                ttl = quote.get_total()
                if ttl:
                    value += ttl
        self.value = value

        if save:
            self.save(None)

    def update_cost(self, save=True):
        po_lines = PurchaseOrderLine.objects.filter(
            component_line_id__in=self.components_list.all().values_list('id', flat=True),
            component_line_content_type=ContentType.objects.get_for_model(ComponentLine))

        price = 0

        for line in po_lines:
            if line.discount == 0:
                if line.get_supplier_discount() > 0:
                    line.discount = line.get_supplier_discount()
                    line.save()

            price += line.get_line_price()

        self.cost = price

        if save:
            self.save(None)

    def save(self, *args, **kwargs):
        self.update_value(save=False)
        self.update_cost(save=False)
        super(Job, self).save(*args, **kwargs)

    def get_absolute_url(self):
        if self.id:
            if self.status.state:
                return reverse(self.status.state.name, args=[self.id])
            else:
                return reverse('repair_created', args=[self.id])
        else:
            return reverse('repair_added')

    def is_order_filled(self):
        po_line_type = ContentType.objects.get_for_model(ComponentLine)
        for line in self.components_list.all():
            try:
                po_line = PurchaseOrderLine.objects.get(
                    component_line_content_type=po_line_type,
                    component_line_id=line.id,
                    purpose="repair")
            except PurchaseOrderLine.DoesNotExist:
                continue

            if not po_line.delivered:
                return False

        return True

    def split(self):
        new_repair = super(Job, self).split()
        # blank bits we don't need
        new_repair.due_date = None
        new_repair.order_number = None
        new_repair.tracking_details = None
        new_repair.tracking_link = None
        #copy the bits we do
        new_repair.part = self.part
        new_repair.SLA = self.SLA
        new_repair.serial_no = self.serial_no
        return new_repair


class JobNote(WorkItemNote):
    item = models.ForeignKey('jobs.Job', related_name='notes')
    upload = models.FileField(upload_to='job_files', null=True, blank=True)


class JobEmail(WorkItemEmail):
    item = models.ForeignKey('jobs.Job', related_name='email_notes')

    def get_absolute_url(self):
        return reverse('li-view-email', kwargs={'model': 'job', 'pk': self.id})

    def get_raw_url(self):
        return reverse('li-raw-email', kwargs={'model': 'job', 'pk': self.id})

1 个答案:

答案 0 :(得分:0)

似乎您有自定义应用email。尝试

>>>import email
>>>print email.__file__

检查电子邮件的导入位置。