dabapps / django-readers

A lightweight function-oriented toolkit for better organisation of business logic and efficient selection and projection of data in Django projects.
https://www.django-readers.org
BSD 2-Clause "Simplified" License
183 stars 7 forks source link

[Solved] How to retrieve nested related items but ordered in a certain way? #72

Closed simkimsia closed 1 year ago

simkimsia commented 1 year ago
def get_mass_upload_template_details_by_id(pk):
    """
    get mass_upload_template by id for details
    """
    spec_for_line_items = [
        "id",
        {
            "product": [
                "cpop_id",
                "serial_number",
                "full_name_description",
                "sheet_name",
                "id",
            ]
        },
        "display_order",
    ]

    spec = [
        "id",
        "name",
        {
            "pricebook": [
                "id",
                "cpop_id",
                "name",
            ]
        },
        {
            "line_items": spec_for_line_items
        },
    ]

    prepare, project = specs.process(spec)
    product_package = prepare(CustomerMassUploadLineItemToQuotationTemplate.objects.all()).get(pk=pk)

    return project(product_package)

I need to retrieve the line_items in order of display_order. How do I do this?

simkimsia commented 1 year ago

As inspired by https://www.django-readers.org/cookbook/#filter-the-set-of-related-instances

I took a wild guess and put pairs.order_by("display_order"),

def get_mass_upload_template_details_by_id(pk):
    """
    get mass_upload_template by id for details
    """
    spec_for_line_items = [
        # add the order_by
        pairs.order_by("display_order"),
        "id",
        {
            "product": [
                "cpop_id",
                "serial_number",
                "full_name_description",
                "sheet_name",
                "id",
            ]
        },

It works

j4mie commented 1 year ago

Glad it works. It would be useful to have an example of this in the cookbook too.

simkimsia commented 1 year ago

Add it 👍

On Tue, 11 Oct 2022 at 23:52, Jamie Matthews @.***> wrote:

Glad it works. It would be useful to have an example of this in the cookbook too.

— Reply to this email directly, view it on GitHub https://github.com/dabapps/django-readers/issues/72#issuecomment-1274918873, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAB32HKVH2TR765GLSVOPTTWCWENVANCNFSM6AAAAAARCNF2P4 . You are receiving this because you modified the open/close state.Message ID: @.***>

--

KimSia @.***