Get ordered field names from peewee Model
Asked Answered
S

3

13

I'd like to use peewee to create records from a csv. It looks like the syntax requires keyword args:

user = User.create(username='admin', password='test')

If the rows in the csv look like (admin, test), it would be convenient to know the field names ('username', 'password') to form a dict to pass in (it looks like I can't pass in a list of the values for the model to infer what the corresponding fields are).

Is there a property of User that has a list of the field names in the order that they are defined?

Thanks

Sacrilege answered 3/6, 2013 at 18:24 Comment(0)
S
19

Looks like it's User._meta.get_field_names()

I just saw someone else mention it in another question.

Sacrilege answered 3/6, 2013 at 18:26 Comment(7)
Note to self: don't use User as a model nameSacrilege
I just stumbled on this question: Why wouldn't you use User as a model name?Antiphonal
It's a reserved word in postgres. Peewee handles it fine, but it makes it trickier to use the console.Sacrilege
Update for those that stumble onto this question: For newer versions of peewee, you need to use User._meta.sorted_fields or User._meta.sorted_field_namesRudolph
I had to use <class>._meta.fields.keys() because sorted_field_names wasn't returning Foreign Keys (sometimes).Banting
@Banting -- that's not correct. Were you expecting it to return back-references or something?Hartwig
@Ian thank, couldn't find in in peewee document. how did you find it?Lithography
H
0

The accepted answer is for an older version of Peewee. The proper way to do this is either:

class SomeModel(db.Model):
    ...

sorted_field_names = SomeModel._meta.sorted_field_names
Hartwig answered 26/12, 2023 at 13:51 Comment(0)
D
-1

The given approved answer did not work for me, but the below code did.

YourModel._meta.columns.keys()
Depersonalization answered 24/12, 2023 at 12:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.