Django: Excluding with limit_choices_to

If you’re using Django, and you’re declaring your model, there are times when you want to use a ManyToMany or ForeignKey field, and limit the display choices in the admin. The usual method is to specify a dictionary where the key is the field name appended with the type of field lookup that you want, and the value is the corresponding lookup value. Then, the behavior you will get is as if you’re using the filter(…) method.

However, there will be times when you want to use limit_choices_to as if you want to use exclude(…). limit_choices_to doesn’t work like exclude. So, you can do the following:

class MyModel(models.Model):
    ...
    groups = models.ManyToManyField(Group,
limit_choices_to = { 'id__in' : Group.objects.exclude(name = 'Exclusion Group Name') })
    ....