filtering the order_by relationship in Django ORM

本秂侑毒 提交于 2019-12-12 06:03:03

问题


In the below, product has many writers through contributor, and contributor.role_code defines the exact kind of contribution made to the product. Is it possible with the Django ORM to filter the contributors referenced by the order_by() method below? E.g. I want to order products only by contributors such that contributor.role_code in ['A01', 'B01'].

Product.objects.filter(
    product_type__name=choices.PRODUCT_BOOK
).order_by(
    'contributor__writer__last_name'    # filter which contributors it uses?
)

回答1:


To filter on specific values, first build your list of accepted values:

accepted_values = ['A01', 'B01']

Then filter for values in this list:

Product.objects.filter(
        product_type__name=choices.PRODUCT_BOOK
    ).filter(
        contributor__role_code__in=accepted_values
    ).order_by(
        'contributor__writer__last_name'
    )


来源:https://stackoverflow.com/questions/28773867/filtering-the-order-by-relationship-in-django-orm

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