如何检查外键是否存在?

时间:2019-09-17 10:36:13

标签: django django-views foreign-keys

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

我该怎么办?

我收到以下代码错误:

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

models.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')

views.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')

1 个答案:

答案 0 :(得分:5)

支票应为:

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处理程序,在 model 层中设置此类逻辑:

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,这会使它更加安全。