Limiting choices in a lookup by exclusion

40 views
Skip to first unread message

Gordon R. Burgess

unread,
Jan 31, 2017, 11:17:52 PM1/31/17
to django...@googlegroups.com

I have this code, and with Django 1.10 it works as expected:

class Location(models.Model):
    name = models.CharField(max_length = 32, unique = True)
    street = models.CharField(max_length = 32)
    detail = models.CharField(max_length = 32, blank = True, null = True)
    city = models.CharField(max_length = 32)
    state = USStateField()
    zip = USZipCodeField()
    phone = models.ManyToManyField(Phone, limit_choices_to = {'type_id':'H'})

but what I'd like to do is restrict the choices of phone numbers for Locations to those that aren't 'C' (cell phones) - I've found some hints, but they're all for older versions of Django - it seems like:

    phone = models.ManyToManyField(Phone, limit_choices_to = {'type_id__ne':'C'})

ought to work - but this provokes a TypeError:

Related Field got invalid lookup: ne

Thanks!

C. Kirby

unread,
Feb 1, 2017, 2:48:29 AM2/1/17
to Django users
django doesn't have an ne operator in the orm. You want to use a negated Q object for your limit_choices_to. try:

from django.db.models import Q

phone = models.ManyToManyField(Phone, limit_choices_to = ~Q(type_id = 'C'))

Melvyn Sopacua

unread,
Feb 1, 2017, 10:04:04 PM2/1/17
to django...@googlegroups.com

And there's 2 other options to consider:

 

  • The ne lookup is actually the first example in the documentation for custom lookups. So you get its implementation for free and can consider adding it.
  • You can extend Field to add exclude_choices() which sets limit_choices_to to the negation of the argument as below - so wrap it with ~Q().

All depending on how isolated your case is in the project/app.

--

Melvyn Sopacua

Reply all
Reply to author
Forward
0 new messages