python - 如果没有被其他对象引用,如何删除对象

标签 python sql django

我有两个与此相似的模型:

class ContactDetails(Model):
  name = models.CharField()
  dept = models.CharField()

class Server(Model):
  ip = models.GenericIPAddressField()                           
  hostname = models.CharField()
  contact = models.ForeignKey(ContactDetails)


ContactDetails对象可能被许多Server对象引用。

当我删除服务器记录时,我还要删除关联的ContactDetails记录。

但仅当没有其他服务器记录引用该ContactDetails记录时。在Django中执行此操作的最佳做​​法是什么?

最佳答案

可能使用pre_delete或post_delete signals

from django.db import models
from django.dispatch import receiver

@receiver(models.signals.post_delete, sender=Server)
def delete_contact(sender, instance, **kwargs):
    if not Server.objects.filter(contact=instance.contact):
        instance.contact.delete()


该实例是已经从数据库中删除的Server实例。

关于python - 如果没有被其他对象引用,如何删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24627841/

相关文章:

python - Beautifulsoup 如果类存在

MySQL 将高度格式转换为厘米

Django 管理员 : search for foreign key objects rather than <select>?

python - DRF API 端点获取 "Authentication credentials were not provided"

django - 迁移Django固定装置?

c# - 将python转换为c#的工具

python - 在 matplotlib 中使用 "contourf"设置颜色条范围

python - 如何在 Python 中导入变量包,如在 PHP 中使用变量变量 ($$)?

mysql - 使用IF语句和子查询的mysql查询中的错误

mysql - 寻找最有效的方法来查询Mysql中的多个电子邮件地址