Insert data from dictionary to table


#1

Hi

I want to insert values from dictionary to table with my view, but I couldn’t find a way to do it.Fields in table and keys in dictionary are same. Does anyone know how to do it ?

Regards

Example :

dict = {
‘name’: ‘John’,
‘age’ : 30,
}

Fields are ‘name’ and ‘age’


(Shekhar Nunia) #2

can you elaborate your question little bit more?


(Vitor Freitas) #3

If the names are exactly the same, you could do something like that:

def example_view(request, person_id):
    update_data = {
        'name': 'John',
        'age': 30
    }
    Person.objects.filter(id=person_id).update(**update_data)

Another option is to set it in a for loop:

def example_view(request, person_id):
    person = Person.objects.get(id=person_id)

    update_data = {
        'name': 'John',
        'age': 30
    }

    for key, value in update_data.items():
        setattr(person, key, value)

    person.save()

#4

Thanks for your answer Vitor.

What should I do if I want to insert new row to table ? Is it just

`Person.objects.create(**dict)` ?

Dict data that I want to write into table is coming from another function. But It misses some fields in my table.Is it possible to add id or another attribute of Person object and insert it with the dict data into the row with objects.create() ?

Example :

Person.objects.create(**dict, height = 180)


(Vitor Freitas) #5

Yes you can do that

Person.objects.create(**dict, height=180)

Or you could also update your dictionary

dict['height'] = 180
Person.objects.create(**dict)

The ** command “expands” a dictionary as keyword arguments.

So this:

params = {
  'x': 10,
  'y': 20
}
myfunction(**params)

Is equivalent to this:

myfunction(x=10, y=20)

#6

It worked correctly.
:+1: