I have two models
class Group(models.Model):
....
and
class User(models.Model):
...
group = models.ManyToManyField(
Group)
Have ManyToMany relation.
What's the best way to prevent delete Group instance if there are some Users with this Group
my solution is :
def delete(self, request, *args, **kwargs):
try:
list_ = []
for user in User.objects.all():
for group in user.group.all():
if group.name not in list_:
list_.append(group.name)
else:
continue
if Group.objects.get(pk=kwargs['pk']).name in list_:
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
else:
return self.destroy(request, *args, **kwargs)
except:
raise ValueError("Error")