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.
- [Django]-Django admin β prevent objects being saved, and don't show the user confirmation message
- [Django]-How to "create or update" using F object?
Source:stackexchange.com