[Django]-Get value for each model field with _meta

2👍

You can obtain the values by using field.get_attname() to obtain the name of the attribute, and then access getattr(self, field.get_attname()):

class BaseModel(models.Model):
        
    # …
    
    def get_values(self):
        return {
            field.name: getattr(self, field.get_attname())
            for field in cls._meta.fields
        }

This will then return a dictionary that maps the field names to the corresponding object.

or as a list of values:

class BaseModel(models.Model):
        
    # …
    
    def get_values(self):
        return [
            getattr(self, field.get_attname())
            for field in cls._meta.fields
        ]

Leave a comment