我有这样的模特:
class Server(Model):
ip = models.GenericIPAddressField()
hostname = models.CharField()
contact = models.ForeignKey(Contact)
note = models.ForeignKey(Note)
class Contact(Model):
name = models.CharField()
dept = models.CharField()
class Note(Model):
subject = models.CharField()
body = models.CharField()
我也有这个post_delete处理程序:
# When deleting a Server, if the Server's Contact doesn't
# reference another Server delete the Contact. Also, do the same
# for note. This ensures no orphaned contacts or notes left in database.
@receiver(models.signals.post_delete, sender=Server)
def delete_contact_note(sender, instance, **kwargs):
if not Server.objects.filter(contact=instance.contact):
instance.contact.delete()
if not Server.objects.filter(note=instance.note):
instance.note.delete()
当通过管理员一次删除多个服务器对象时出现问题 - 它在post_delete调用中失败并显示以下消息:
DoesNotExist: Contact matching query does not exist.
好像在Server对象之前删除了Contact对象?
如果我尝试一次删除一个服务器对象(再次通过管理员),它可以正常工作。如果我一次删除很多对象,似乎只会发生这种情况。
造成这种情况的原因是什么?
我该如何解决这个问题?
答案 0 :(得分:1)
尝试使用try / expect:
@receiver(models.signals.post_delete, sender=Server)
def delete_contact_note(sender, instance, **kwargs):
try:
if not Server.objects.filter(contact=instance.contact):
instance.contact.delete()
if not Server.objects.filter(note=instance.note):
instance.note.delete()
expect ObjectDoesNotExist:
pass # U can change this command
这不是解决方案,只是这个片段帮助它。但是你可以捕获所有对象;)