Home > Blockchain >  Django Iteration through the fields of particular instance of the model
Django Iteration through the fields of particular instance of the model

Time:01-31

I'm new in django. My goal is to create a dictionary with keys taken from table and values taken from particular instance of the model which amongs the others contains fields we can meet in table. Is any way to iterate through fields of the model's instace to do that?

My idea as you see below doesn't work because particular instance represented as i doesn't recognize variable j as his field.

Any Idea?

my_fields=['car','model','age']
my_dict={} #I would like it to look like my_dict={'car':'Toyota','model':'Corolla','age':2}

class Cars(models.Model):
     car=models.CharField(max_length=40)
     model=models.CharField(max_length=40)
     age=models.IntegerField()
     country=models.CharField(max_length=40)
     amounts_of_doors=models.IntegerField()

     
#particular instance
Object { model: "cars.Car", pk: 1, fields: {'car':'Toyota','model':'Corolla','age':2}}

#code I have tried

for i in Cars.objects.all():
    if i.car=='Toyota:
       for j in my_fields:
            my_dict[j]=i.j <==it doesn't work 

CodePudding user response:

I guess you could convert your model instance using model_to_dict. then you could access to its keys, value like

for i in Cars.objects.all():
    if i.car=='Toyota':
       for j in my_fields:
            my_car_dict = model_to_dict(i)
            my_dict[j] = my_car_dict[j]

Or you could use gettattr directly on your model instance

for i in Cars.objects.all():
    if i.car=='Toyota':
       for j in my_fields:
            my_dict[j] = getattr(i, j)

CodePudding user response:

You don't have to do any of this when you have values that get model fields as key and values as instances values.

toyota = Cars.objects.filter(id=1).values()
# do something with toyota

Still if you want to get model fields just do it with this Car._meta.get_fields()

  •  Tags:  
  • Related