Rejected
Rejected

Reputation: 4491

Python: Dumping Database Data with Peewee

Background

I am looking for a way to dump the results of MySQL queries made with Python & Peewee to an excel file, including database column headers. I'd like the exported content to be laid out in a near-identical order to the columns in the database. Furthermore, I'd like a way for this to work across multiple similar databases that may have slightly differing fields. To clarify, one database may have a user table containing "User, PasswordHash, DOB, [...]", while another has "User, PasswordHash, Name, DOB, [...]".

The Problem

My primary problem is getting the column headers out in an ordered fashion. All attempts thus far have resulted in unordered results, and all of which are less then elegant.

Second, my methodology thus far has resulted in code which I'd (personally) hate to maintain, which I know is a bad sign.

Work so far

At present, I have used Peewee's pwiz.py script to generate the models for each of the preexisting database tables in the target databases, then went and entered all primary and foreign keys. The relations are setup, and some brief tests showed they're associating properly.

Code: I've managed to get the column headers out using something similar to:

    for i, column in enumerate(User._meta.get_field_names()):
        ws.cell(row=0,column=i).value = column

As mentioned, this is unordered. Also, doing it this way forces me to do something along the lines of

    getattr(some_object, title)

to dynamically populate the fields accordingly.

Thoughts and Possible Solutions

Feel free to tell me I'm doing it all wrong or suggest completely different ways of doing this, I'm all ears. I'm very much new to Python and Peewee (ORMs in general, actually). I could switch back to Perl and do the database querying via DBI with little to no hassle. However, it's libraries for excel would cause me as many problems, and I'd like to take this as a time to expand my knowledge.

Upvotes: 6

Views: 3440

Answers (1)

coleifer
coleifer

Reputation: 26235

There is a method on the model meta you can use:

for field in User._meta.get_sorted_fields():
    print field.name

This will print the field names in the order they are declared on the model.

Upvotes: 7

Related Questions