[Answered ]-Limit a Django ManyToMany by field value

1👍

This functionality is not built into the Django framework, but you can create your own filter inside the view method.

For example,

MAXKEYS = 3

def addNewKey(request):
  if request.user.is_authenticated():
    deviceRequest = Device.objects.get(pk = request.GET["deviceId"])
    keys = Key.objects.filter(device = deviceRequest)

    if len(keys) < MAXKEYS:
      #add new key reference
    else:
      #return an error or something

  else:
    #return user is not authenticated error message
👤Jason

1👍

You can listen to the m2m_changed django signal which gets sent every time you add a device to the Key instance.

It will look something like this:

def device_added(sender, **kwargs):
     print "action == %s"%kwargs['action'] # You should intercept when action is 'pre_add'
     print "keyInstanceCount == %s"%kwargs['instance'].count # this is where you can check the current count field and raise your exception if it is exceeding the limit

m2m_changed.connect(device_added, sender=Key.device.through)

Once you connect m2m_changed to device_added, everytime you add a device to a key instance device_added function gets notified as well.

Leave a comment