Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django: get model's fields name

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading