Django limit_choices_to for multiple fields with “or” condition

此生再无相见时 提交于 2020-05-26 10:51:46

问题


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).


回答1:


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



来源:https://stackoverflow.com/questions/30181079/django-limit-choices-to-for-multiple-fields-with-or-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!