Hi Django community,
how can I access model fields dynamically during run time? At the moment I just know how to access model fields explicitly. An example: class Example(models.Model): text = models.CharField(max_length=50) comment = models.CharField(max_length=50) def return_info(self): return self.text, self.comment But I would like to dynamically parse over the existing fields and create the string automatically. Something like this: class Example(models.Model): text = models.CharField(max_length=50) comment = models.CharField(max_length=50) FIELDS_ORDERED = ['text', 'comment'] # maybe even not this explicit, could also use _meta, but I do explicitly because I don't want id/pk inside def return_info(self): a = '' for field in self.FIELDS_ORDERED: a += self.field # I know this does not work, but I would like I know about getattr(), but therefore I need an instance which I think I cannot self reference inside the model. Note: The reason I am approaching this is: I use django REST framework (DRF) and want to add a read-only dynamic field to a model. Unfortunately, DRF does not allow me to call a model manager class inside the serializer (idk why), so I can only call a method directly from the model. An example: class ExampleSerializer(serializers.ModelSerializer): info = serializer.CharField(source='return_info', read_only=True) class Meta: model = Example Does anyone can help me here? Thanks for any reply! BR enrico -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/db4c70e6-486c-4278-bb37-dec43391f10c%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.