【发布时间】:2020-01-18 05:06:50
【问题描述】:
在这里,我有一个名为 Staff 的模型,它与 django User 模型具有 OneToOne 关系,并且与 Organization 模型具有 ForeignKey 关系。在删除组织时,我想检查组织是否存在于 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')
【问题讨论】:
-
请您显示完整的错误跟踪。
标签: django django-views foreign-keys