filtering the order_by relationship in Django ORM

2019-09-07 21:43发布

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条回答
家丑人穷心不美
2楼-- · 2019-09-07 21:46

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'
    )
查看更多
登录 后发表回答