Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how many fields a model has

Tags:

django

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?

like image 979
Prova12 Avatar asked Aug 02 '26 04:08

Prova12


1 Answers

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.

like image 117
Willem Van Onsem Avatar answered Aug 05 '26 11:08

Willem Van Onsem