Dynamic attribute call in model

32 views
Skip to first unread message

enrico baranski

unread,
Nov 3, 2018, 6:56:08 AM11/3/18
to Django users

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

Reply all
Reply to author
Forward
0 new messages