简体   繁体   中英

how can i serialize all model fields inside model in django

I have the model object available inside the django template as Obj .

now i want a generic function which can display all fields in and value like this

{% for instance in data %}
    {% for field, value in instance.fields.items %}
        {{ field }}: {{ value }}
    {% endfor %}
{% endfor %}

I tried this in Model

def objectdata(self):
        return serializers.serialize( "python", self.objects.all() ) 

Then i get the maximum recursion error because it was looping over my this function.

I can't edit the view. is there any way that i can add something in Model only to make that working

Some tips : If instance is a django Model instance, the list of fields is in instance._meta.fields . You can use it to walk trough the instance and get the list you want :

def objectdata(self):
    k_w = {}
    for field in self._meta.fields :
        k_w[field.name] = self.__getattr__(field.name)

    return k_w

Be careful with some field like ForeignKey, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM