gpt4 book ai didi

django - 如何检查外键是否存在?

转载 作者:行者123 更新时间:2023-12-03 21:18:13 25 4
gpt4 key购买 nike

这里我有一个模型叫 Staff与 django 有 OneToOne 关系 User模型和外键与 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')

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

最佳答案

支票应该是:

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在还有相关人员的地方,这使得它更安全。

关于django - 如何检查外键是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57972471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com