Exporting items from a model to CSV Django / Python

前端 未结 9 2042
死守一世寂寞
死守一世寂寞 2021-02-03 09:52

I\'m fairly new to django and Python and want to be able to export a list of items in my model i.e products. I\'m looking at the documentation here - https://docs.djangoproject.

9条回答
  •  独厮守ぢ
    2021-02-03 10:48

    Have a look at the python csv module.

    You'll probably want to get the models fields with

    def get_model_fields(model):
        return model._meta.fields
    

    Then use

    getattr(instance, field.name)
    

    to get the field values (as in this question).

    Then you'll want something like

    with open('your.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile)
        # write your header first
        for obj in YourModel.objects.all():
            row = ""
            for field in fields:
                 row += getattr(obj, field.name) + ","
            writer.writerow(row)
    

    It's a bit verbose (and untested), but it should give you an idea. (Oh and don't forget to close your file)

提交回复
热议问题