Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django limit_choices_to for multiple fields with "or" condition

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

With below version, I only got 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).

like image 375
hercules.cosmos Avatar asked May 12 '15 03:05

hercules.cosmos


1 Answers

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

like image 79
moonstruck Avatar answered Sep 28 '22 05:09

moonstruck