[Answer]-Django Related and NoRelated on a ManyToMany

1👍

Inside the FenceGroup class, define these methods:

from django.db.models import Q

def related(self):
    'returns all related Fences'
    return FenceShip.objects.filter(fence_group=self)

def non_related(self):
    'returns all non-related Fences'
    return FenceShip.objects.filter(~Q(fence_group=self))

def fences(self):
    'returns a list of pairs: (fence, related) where related is True/False'
    return [(fence, bool(fence.fence_group==self)) for fence in FenceShip.objects.all()]

Leave a comment