Django: get model's fields name

Question:

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?

Asked By: Orl13

||

Answers:

You can use either get all fields using get_fields() or get a specific field using the get_field('field_name') function from model _meta API.

Usage:

fields = model._meta.get_fields()
my_field = model._meta.get_field('field_name')

I believe this will return a list of Field objects. To get the value of each field from the instance, use getattr(instance, field.name).

Ref.: Retrieving all field instances of a model

Answered By: Ashrof

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]
Answered By: puchal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.