简体   繁体   中英

Get all fields except one

I am currently displaying my fields in the django admin interface via model._meta.get_all_field_names() . Now this works fine, but it also displays the Primary key of the dataset (which doesn't look very nice in my opinion).

So my question is: Is there a "lazy" way to get all fields except for one/multiple? Or do I have to write every single field except for the one(s) I don't want to have displayed into a list_display = array_of_fields_to_be_displayed

You can use model._meta.fields attribute which is a list of Field instances:

[field.name for field in model._meta.fields if not field.primary_key]

every Field has primary_key attribute ( True if the field is the primary key) and name attribute (well, name of the field).

Working example on auth.models.User :

>>> [field.name for field in User._meta.fields if not field.primary_key]
['password', 'last_login', 'is_superuser', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active', 'date_joined']

There is no id field in the output. Probably a good thing.

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