Prova12
Prova12

Reputation: 653

Count how many fields a model has

I am wondering if there is a way to know how many fields a model contains.

Example:

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

I can count it but I would like to know if there is an in-built method that allows me to do so.

Ideally the quesry/code would be:

Post.number_of_fieds-->output--> 4

Does such a thing exist?

Upvotes: 3

Views: 54

Answers (2)

shafikshaon
shafikshaon

Reputation: 6404

You can try this

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

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476997

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.

Upvotes: 4

Related Questions