Home > Enterprise >  ManytoMany relation in Django?
ManytoMany relation in Django?

Time:04-06

I have two models

class Group(models.Model):
    ....

and

class User(models.Model):
...
group = models.ManyToManyField(
    Group)

have ManyToMany relations

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")

I hope there are much better solution.

CodePudding user response:

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 Groups 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.

  • Related