我尝试从365 api获取一些消息并将其保存在我的InitialMessage模型上。我什么时候尝试这样做,我不断收到这条消息:
django.db.utils.IntegrityError:(' 23000'," [23000] [Microsoft] [SQL Server Native Client 11.0] [SQL Server]违反UNIQUE KEY约束&#39 ; UQ__assignme__F9CC0897DC370444'。无法在对象中插入重复键' dbo.assignment_initialmessage'。重复键值为()。(2627)(SQLParamData)")
UNIQUE KEY约束是指与模型Claim的关系(claim = models.OneToOneField(Claim,null = True,blank = True,default = None)
这是我的模特:
class InitialMessage(models.Model):
json = models.TextField()
att_url = models.CharField(max_length = 254, default='https://outlook.office365.com/api/v1.0/me/messages/{0}/attachments')
send_url = models.CharField(max_length = 254, default='https://outlook.office365.com/api/v1.0/me/sendmail')
update_url = models.CharField(max_length = 254, default='https://outlook.office365.com/api/v1.0/me/messages/{0}')
id_email = models.CharField(max_length = 254,unique=False)
subject = models.TextField()
body_content = models.TextField()
body_type = models.TextField()
importance = models.CharField(max_length = 254)
hasAttachments = models.BooleanField(default=False)
parentFolderId = models.CharField(max_length = 254)
e_from = models.TextField()
sender = models.TextField()
conversationId = models.TextField()
categories = models.TextField()
dateTimeSent = models.DateTimeField()
dateTimeReceived = models.DateTimeField()
status = models.CharField(max_length=2, choices=INITIALMESSAGE_STATUS, default='P')
claim = models.OneToOneField(Claim, null=True, blank=True, default=None)
def load_json(self):
m_json = json.loads(self.json)
try:
email = InitialMessage.objects.get(id_email = m_json['Id'])
except InitialMessage.DoesNotExist:
email = None
if email is None:
self.id_email = m_json['Id']
self.subject = m_json['Subject']
self.body_content = m_json['Body']['Content']
self.body_type = m_json['Body']['ContentType']
self.importance = m_json['Importance']
self.hasAttachments = m_json['HasAttachments']
self.parentFolderId = m_json['ParentFolderId']
self.e_from = m_json['From']
self.sender = m_json['Sender']
self.conversationId = m_json['ConversationId']
self.categories = m_json['Categories']
self.dateTimeSent = m_json['DateTimeSent']
self.dateTimeReceived = m_json['DateTimeReceived']
self.save()
else:
m_json = 'Duplicated'
return m_json
这是我用来保存每封新电子邮件的代码:
log.debug('fetching messages.')
response = requests.get(self.inbox_url,auth=self.auth,params={'$filter':self.filters})
log.info('Response from O365: %s', str(response))
for message in response.json()['value']:
M = InitialMessage(json = json.dumps(message)).load_json()
log.debug('all messages retrieved and put in to the list.')
return True
有任何想法吗?谢谢你的帮助!