Django: Database column not updating from variable, taking it as hardcoded name

Question:

I have the following code for updating a database column.

def update_itemamadeus(check_flight_differences):

    for item_id, flight_details in check_flight_differences.items():

        for field, value in flight_details.items():

            ItemAmadeus.objects 
                .filter(
                    Q(id=item_id)
                ) 
                .update(
                    field = value
                )
    return

It’s taking ‘field’ not as the variable it should be which is ‘code_airport_from_id’.

item_id = 130
field   = code_airport_from_id
value   = BCN

The dreaded yellow screen error:

enter image description here

Can this be achieved?

Asked By: Duvan Smuts

||

Answers:

You need to convert the parameters as dictionary and pass it through function by unpacking them, like this:

ItemAmadeus.objects 
            .filter(
                Q(id=item_id)
            ) 
            .update(
                **{field:value}
            )

This article on geeksforgeeks has some examples of unpacking.

Answered By: ruddra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.