Search code examples
pythondjangoclassattributesattr

Count number of attributes of a class


I want to make a fully dynamic table which adjusts its self number of columns depending on which type of object I'm passing in the view.

What I tried is:

from Food.models import Food


for field in Food:
    # Count how many fields do my class Food has.

But PyCharm is showing the following error:

Expected 'collections.Iterable', got 'Type[Food]' instead.

Pretty obvious since it's not an actual initialized object. But how can I achieve this? Thanks!


Solution

  • You can use Food._meta.fields to get a list of fields on the model.