【发布时间】:2013-12-13 21:17:42
【问题描述】:
我将 Django 与多个数据库一起使用。我有一个“预览”数据库,它接收用户上传的消息,这些消息必须由管理员预览并“接受”,此时它们被提交到“默认”生产数据库。以下视图应该做到这一点,但我得到一个错误。每个 newSentenceModel 对每个 newMessageSegment 都有一个外键,每个 newMessageSegment 对每个消息都有一个外键。如果管理员接受内容,我想将每个项目移动到新数据库,然后删除预览数据库中的旧条目。请帮忙!谢谢 -
这是错误:
instance is on database "preview", value is on database "default"
错误信息出现在这一行:
newMessageSegment.msg = newMessage # Setup the foreign key to the msg itself
这里是视图函数:
## This view is used when the admin approves content and clicks on the "accept content" button when reviewing
## a recent upload - it saves the data to the production database
def accept_content(request, msg_id=None):
if msg_id == None: # If for some reason we got a None, then it's not a valid page to accept so redirect home
return HttpResponseRedirect("/") # Redirect home
msgList = Message.objects.using('preview').all() # Get all Messages
msgSegmentList = MessageSegment.objects.using('preview').all() # Get all MessageSegment Objects
sentenceModels = SentenceModel.objects.using('preview').all() # Get all SentenceModels
for msgs in msgList: # Iterate all msgs
if int(msgs.id) != int(msg_id): # Don't care if it is not the msg needing review
continue # Short Circuit
msgPrimaryKey = msgs.pk # Extract the primary key from this msg to restore later
msgs.pk = None # Erase the primary key so we can migrate databases properly
newMessage = msgs # This is the msg to transfer to the new one
newMessage.save(using='default') # Save the item to the production database
for msgSegment in msgSegmentList: # Iterate all msg segments for this msg
if msgSegment.msg_id == msgPrimaryKey: # Check the foreign keys on the msg segment to msg connection
newMessageSegment = msgSegment # Define a new msg segment
msgSegment.pk = None # Erase the primary key so we can assign it properly
newMessageSegment.pk = None # Erase the primary key so we can assign it properly
newMessageSegment.msg = newMessage # Setup the foreign key to the msg itself
newMessageSegment.save(using='default') # Save the item to the production database
for sentenceModel in sentenceModels: # Iterate all sentences for this msg segment
if sentenceModel.msg_segment_id == msgSegment.id: # Determine which sentences are for this msg segment
newSentenceModel = sentenceModel # Define the newSentenceModel
newSentenceModel.msg_segment = newMessageSegment # Setup the foreign key to the msg segment
newSentenceModel.save(using='default') # Save the item to the production database
sentenceModel.delete(using='preview') # Delete the item from the review database
msgSegment.delete(using='preview') # Delete the item from the review database
msgs.pk = msgPrimaryKey # Restore the key so we can delete it properly
msgs.delete(using='preview') # Delete the item from the review database
return HttpResponseRedirect("/")
【问题讨论】:
标签: python django django-models django-views django-orm