Django iterate model object dynamically

Django -- Posted on Feb. 4, 2024

This snippet can be used to iterate a model object in django  dynamically 

              
                def get_obj(obj):
    from django.db import models
    app_label = obj._meta.app_label
    print(app_label)
    fields = obj._meta.get_fields()
    for field in fields:
        if hasattr(obj,field.name):
            value = getattr(obj,field.name)
            if isinstance(field,models.ForeignKey):
                print(field.remote_field.model)
            elif isinstance(value,models.Manager):
                related_objects = value.get_queryset()
                for r_obj in related_objects:
                    print(r_obj)
            else:
                print("name==>",field.name, "value==>",value)
  
my_obj = Model.objects.get(id=1)
get_obj(my_obj)
                  
   
            

Related Posts