如何检查外键是否存在?

Hel*_*llo 4 django foreign-keys django-views

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

我该怎么做 ?

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

Exception Type: TypeError
Exception Value:    
argument of type 'bool' is not iterable
Run Code Online (Sandbox Code Playgroud)

模型.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')
Run Code Online (Sandbox Code Playgroud)

视图.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')
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 6

支票应该是:

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')
    # ...
Run Code Online (Sandbox Code Playgroud)

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

def delete_organization(request, pk):
    organization = get_object_or_404(Organization, pk=pk, is_staff__isnull=True)
    # ...
Run Code Online (Sandbox Code Playgroud)

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

根据您编写的逻辑,您要防止在仍有员工的情况下删除组织。您也可以使用作为处理程序在模型层中设置此类逻辑:models.PROTECTon_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')
Run Code Online (Sandbox Code Playgroud)

现在 Django 将帮助您确保您不会意外删除Organization仍然有相关人员的地方,这使其更安全。