首页 > 解决方案 > 如何检查外键是否存在?

问题描述

在这里,我有一个模型Staff,它与 django 模型具有 OneToOne 关系,User并且与模型有 ForeignKey 关系。在Organization这里,在删除组织时,我想检查组织是否存在于 Staff 模型中。如果它存在于 Staff 模型中,那么我不想删除,但如果它在其他表中不存在,那么只有我想删除。

我该怎么做 ?

我使用以下代码收到此错误:

Exception Type: TypeError
Exception Value:    
argument of type 'bool' is not iterable

模型.py

class Organization(models.Model):
    name = models.CharField(max_length=255, unique=True)
    slug = AutoSlugField(unique_with='id', populate_from='name')
    logo = models.FileField(upload_to='logo', blank=True, null=True)

class Staff(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff')
    name = models.CharField(max_length=255, blank=True, null=True)
    organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True,
                                     related_name='staff')

视图.py

def delete_organization(request, pk):
    organization = get_object_or_404(Organization, pk=pk)
    if organization in organization.staff.all().exists():
        messages.error(request,"Sorry can't be deleted.")
        return redirect('organization:view_organizations')
# also tried
# if organization in get_user_model().objects.filter(staff__organization=organizatin).exists():
    elif request.method == 'POST' and 'delete_single' in request.POST:
        organization.delete()
        messages.success(request, '{} deleted.'.format(organization.name))
        return redirect('organization:view_organizations')

标签: djangodjango-viewsforeign-keys

解决方案


检查应该是:

def delete_organization(request, pk):
    organization = get_object_or_404(Organization, pk=pk)
    if organization.staff.exists():
        messages.error(request, "Sorry can't be deleted.")
        return redirect('organization:view_organizations')
    # ...

但是,您可以通过在以下内容中进行适当的过滤来优化上述内容get_object_or_404

def delete_organization(request, pk):
    organization = get_object_or_404(Organization, pk=pk, is_staff__isnull=True)
    # ...

如果组织不存在,或者组织存在但仍有一些员工,这将引发 404。

根据您编写的逻辑,您希望防止在仍有人员的情况下删除组织。你也可以在模型层中设置这样的逻辑,通过使用models.PROTECT作为on_delete处理程序:

class Staff(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff')
    name = models.CharField(max_length=255, blank=True, null=True)
    organization = models.ForeignKey(Organization, on_delete=models.PROTECT, blank=True, related_name='staff')

现在 Django 将帮助您强制您不要意外删除Organization仍然存在相关人员的地方,这使其更加安全。


推荐阅读