[Django]-Count how many fields a model has

4πŸ‘

βœ…

To the best of my knowledge, there is no builtin, you can obtain the fields with:

>>> len(Post._meta.fields)
5

We can define that on a BaseModel class and subclass this, to make such function available to all subclasses:

class BaseModel(models.Model):

    class Meta:
        abstract = True

    @classmethod
    def number_of_fields(cls):
        return len(cls._meta.fields)

class Post(BaseModel):
    title = models.TextField()
    body = models.TextField()
    sub_title = models.TextField()
    summary = models.TextField()

The .fields return an ImmutableList of fields defined on that model. We can use .get_fields() to take into account the relations that are targetting that model as well.

Then we can query like:

>>> Post.number_of_fields()
5

Note however that this will return 5, since the model has an (implicit) primary key here.

2πŸ‘

You can try this

>>> Post._meta.fields.__len__()
5
πŸ‘€shafikshaon

Leave a comment