简体   繁体   中英

How to update data in django table from csv file while keeping the primary key value as it is.?

I have a table which already contains some data in it. Now i want to upload new data from a csv file and want to update some of the previous values of that table. I am using django 1.3 and sqlite3 as database. But i am not able to update the table.

If you do not want to change Primay key values or do not to add new objects to the table, which could be duplicate of the old info - then you need some kind of data which you can use as lookup parameters in your database.

If you have model which represents this data, then its really easy using

m = Model.objects.get(somecolumn = somedata)
m.someothervalue = someotherdata
m.save()

But why include django in this anyway? If you have CSV table, then updating this info is really a case of writing queries. and programs like Excel and openoffice make this very easy. If you already have data in CSV format, then just open the data as spreadsheet and use excels/openoffice's Concactenate function to create update queries

Update mytable set value1 = data1, value2 = data2 where somevalue = somedata;

If you used openoffice for this, then openoffice has this nifty Text to columns function (under data in program menu), which turns concactenated values into string. Then you can copypaste those strings into command prompt or phppgadmin and run.. and voila, you get updated data in your database.

Edit (In response to you comment.):

Look into this: https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

If you want to use django for this, then use get_or_create. But you need to remember here, that if any of the parameters you use in get_or_create method have changed, then new object will be created. Thats why i said in the beginning of the post, that you need some kind of data, which will not change.

for example (taken from the link above)

obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
                  defaults={'birthday': date(1940, 10, 9)})

will create new obj(Person) when used first time. But if used 2nd time and the date has changed, then new Person with same name and last name but new date will be created.

So to avoid this, you'll still need to do something like

obj.someothervalue = someotherdata
obj.save()

if you want to have more control over the data, that could have been changed.

Alan.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM