Django - 更新或创建语法帮助(错误)

时间:2016-12-13 08:16:36

标签: django

我按照(https://docs.djangoproject.com/en/1.10/ref/models/querysets/#update-or-create)按照查询集文档中的指南进行了操作,但我认为我遇到了错误:

我的脚本会检查来自我们ISP的维护电子邮件的收件箱,然后在订阅时向我们发送日历邀请,并为数据库添加维护。

有时我们会获得已计划维护的更新,然后我需要使用新的日期和时间更新数据库,因此我尝试使用“更新或创建”查询集,并且需要使用ref no来自要更新或创建记录的电子邮件

#Maintenance
    if sender.lower() == 'maintenance@isp.com':
        print 'Found maintenance in mail: {0}'.format(subject)
        content = Message.getBody(mail)
        postcodes =  re.findall(r"[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}", content)
        if postcodes:
            print 'Found Postcodes'
        else:
            error_body = """
            Email titled: {0}
            With content: {1}
            Failed processing, could not find any postcodes in the email
            """.format(subject,content)
            SendMail(authentication,site_admins,'Unprocessed Email',error_body)
            Message.markAsRead(mail)
            continue
        times = re.findall("\d{2}/\d{2}/\d{4} \d{2}:\d{2}", content)
        if times:
            print 'Found event Times'
        e_start_time = datetime.strftime(datetime.strptime(times[0], "%d/%m/%Y %H:%M"),"%Y-%m-%dT%H:%M:%SZ")
        e_end_time = datetime.strftime(datetime.strptime(times[1], "%d/%m/%Y %H:%M"),"%Y-%m-%dT%H:%M:%SZ")

        subscribers = []
        clauses = (Q(site_data__address__icontains=p) for p in postcodes)
        query = reduce(operator.or_, clauses)
        sites = Circuits.objects.filter(query).filter(circuit_type='MPLS', provider='KCOM')
        subject_text = "Maintenance: "
        m_ref = re.search('\[(.*?)\]',subject).group(1)

        if not len(sites):
            #try use first part of postcode
            h_pcode = postcodes[0].split(' ')
            sites = Circuits.objects.filter(site_data__postcode__startswith=h_pcode[0]).filter(circuit_type='MPLS', provider='KCOM')

        if not len(sites):   
            #still cant find a site, send error
            error_body = """
            Email titled: {0}
            With content: {1}
            I have found a postcode, but could not find any matching sites to assign this maintenance too, therefore no meeting has been sent
            """.format(subject,content)
            SendMail(authentication,site_admins,'Unprocessed Email',error_body)
            Message.markAsRead(mail)
            continue
        else:
            #have site(s) send an invite and create record
            for s in sites:
                create record in circuit maintenance
                maint = CircuitMaintenance(
                    circuit = s,
                    ref = m_ref,
                    start_time = e_start_time,
                    end_time = e_end_time,
                    notes = content
                    )
                maint, CircuitMaintenance.objects.update_or_create(ref=m_ref)
                #create subscribers for maintenance

m_ref,是与更新匹配的唯一字段,但每次我在测试中运行时都会得到

sites_circuitmaintenance.start_time may not be NULL

但是我确定了吗?

1 个答案:

答案 0 :(得分:1)

如果要更新某些字段,前提是存在具有特定值的记录,则需要明确提供默认值以及字段名称。

您的代码应如下所示:

CircuitMaintenance.objects.update_or_create(default=
   {'circuit' : s,'start_time' : e_start_time,'end_time' : e_end_time,'notes' : content}, ref=m_ref)

您看到的特定错误是因为update_or_create正在创建一个对象,因为不存在rer = m_ref的对象。但是,您没有为所有非空字段传递值。上面的代码就是那个。