Reputation: 695
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")
Upvotes: 2
Views: 72
Reputation: 476614
You can check if the Group
got at least one user with:
def delete(self, request, *args, **kwargs):
items, __ = Group.objects.filter(pk=selk.kwargs['pk'], user=None).delete()
if items:
return Response(status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
This will filter and only retrain Group
s that are empty. If n
is thus 0
then it will take the else
case, and return a 405. In case n
is greater than zero (in this specific case it will always be one), then it will remove that Group
record and return a HTTP 200 response.
Upvotes: 1