19

I am trying to limit choices for a field, by checking values of the two columns, share_holder and distributor. If either of them is true, then I want that choice.

With the below version, I only get choices satisfying both conditions ('share_holder': True AND 'distributor': True).

limit_choices_to={'share_holder': True, 'distributor': True}

However, I need choices for ('share_holder': True OR 'distributor': True).

Dave Mackey
  • 4,306
  • 21
  • 78
  • 136
hercules.cosmos
  • 265
  • 1
  • 3
  • 10

1 Answers1

32

You can use Q objects to achieve this.

from django.db.models import Q


limit_choices_to=Q(share_holder=True) | Q(distributor=True)

Official docs on ForeignKey.limit_choices_to

moonstruck
  • 2,729
  • 2
  • 26
  • 29
  • 1
    Thanks a lot, worked perfect. Could Q objects be used for filtering a field based on other fields of same object. For example, after first field value is selected (such as "animals"), then in second field I only want to show list of animals, not all living things. – hercules.cosmos May 13 '15 at 12:42
  • Q objects is really powerful for complex lookups. Unfortunately I've failed to understand your requirement. If you please tell me little bit detail I'll try to construct the queryset. – moonstruck May 13 '15 at 13:08
  • assume my object is something like class product() with fields of product_class, and product_name. Once user select the product class value, the choices of the product_name should be filtered by the selected product_class. – hercules.cosmos May 13 '15 at 13:14
  • For such situation you may use chain filters like `Product.objects.filter(product_class='class_value').filter(product_name='name_value')` [django-filter](https://github.com/alex/django-filter) is handy package for regular filtering needs. – moonstruck May 13 '15 at 13:31
  • 1
    To clarify my question, posted a new question [here](http://stackoverflow.com/questions/30238500/django-limit-choices-to-by-same-objects-field-value). Having difficulty to get the value of the current instance. – hercules.cosmos May 14 '15 at 13:23