I am trying to create a table in react that uses as table information from a django backend.
I would like to fetch the table’s columns from the API, so I tried updating the model:
class Activity(models.Model):
aid = models.AutoField(primary_key=True)
uid = models.ForeignKey(USER_MODEL, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT,
db_column="uid")
rid = models.IntegerField()
action = models.TextField(max_length=254, blank=True, null=True)
time = models.TextField(max_length=254, blank=True, null=True)
table = models.TextField(max_length=254, blank=True, null=True)
class Meta:
managed = False
db_table = "activity"
@property
def fields(self):
return [f.name for f in self._meta.fields]
I am trying to use fields()
as the method to get all the model’s "column" names, so that I can place them in the API’s response, but it does not work.
How can I get a django model’s field names from the model’s meta?
>Solution :
If you want to have method that get’s all field names inside model class I would suggest to changing fields
from property to classmethod
class Activity(models.Model):
aid = models.AutoField(primary_key=True)
uid = models.ForeignKey(USER_MODEL, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT,
db_column="uid")
rid = models.IntegerField()
action = models.TextField(max_length=254, blank=True, null=True)
time = models.TextField(max_length=254, blank=True, null=True)
table = models.TextField(max_length=254, blank=True, null=True)
class Meta:
managed = False
db_table = "activity"
@classmethod
def get_field_names(cls):
return [f.name for f in cls._meta.fields]