Say for example you have the following model:
from django import models class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author) date_published = models.DateTimeField(default=datetime.datetime.now())
Then you wanted to get all fields or field names of the Book model.
Solution:
You can actually do two things.
First:
If you wanted to get all fields as an object, you can add the following as a method in your Book model:
If you wanted to get all fields as an object, you can add the following as a method in your Book model:
def get_model_fields(self): return self._meta.fields
Second:
If you wanted to get all field names of the Book model, then you can add the following method:
If you wanted to get all field names of the Book model, then you can add the following method:
def get_model_field_names(self): return self._meta.get_all_field_names()
Note:
There is a big difference between the two methods above. The first one returns a list of objects based on Book model while the second one returns a list of strings so use them according to your needs.
No comments:
Post a Comment