djangoloopsdjango-modelsfield

Iterate through Django models fields with for loop


I have a model in Django named models_bdc

models.py

class models_bdc(models.Model):


    id_bdc = models.CharField(primary_key=True, max_length=50)

    bdc_index_line_1 = models.CharField(max_length=50)
    bdc_quantity_1 = models.CharField(max_length=20)
    bdc_description_1 = models.CharField(max_length=50)
    bdc_index_line_2 = models.CharField(max_length=50)
    bdc_quantity_2 = models.CharField(max_length=100)
    bdc_description_2 =  models.CharField(max_length=100)
    bdc_index_line_3 = models.CharField(max_length=50)
    bdc_quantity_3 = models.CharField(max_length=100)
    bdc_description_3 = models.CharField(max_length=100)

In my view I would like to iterate through the fields with a for loop and replace the digit by the i counter value

It would look like something like :

views.py

queryset = models_bdc.objects.filter(id_bdc=1)

[...]

for i in range(3):
   models_bdc.bdc_index_line_ + i
   models_bdc.bdc_quantity_ + i
   models.bdc.bdc_description_ + i

But it's not working.

Is there a way to do this ?

Thanks


Solution

  • Ok so first off If you try to access a single object you should use get instead of filter since get returns a single object whereas filter returns a queryset.

    instance = get_object_or_404(models_bdc, id_bdc='1')  # Get single object or 404 if not found
    

    As for the loop you can dynamically access the fields of a Django model instance using Python's getattr function within your loop. Here's how you can achieve this in your view:

    def your_view(request):
        queryset = models_bdc.objects.filter(id_bdc='1')  # Assuming '1' is a valid id_bdc
        if queryset.exists():
            instance = queryset.first()
    
            for i in range(1, 4):  # Range should be from 1 to 4 because your fields are indexed from 1 to 3
                index_field = f'bdc_index_line_{i}'
                quantity_field = f'bdc_quantity_{i}'
                description_field = f'bdc_description_{i}'
    
                index_value = getattr(instance, index_field)
                quantity_value = getattr(instance, quantity_field)
                description_value = getattr(instance, description_field)
    
                # Replace or process the values as needed
                print(index_value, quantity_value, description_value)
    
    

    If you try to implement this for multiple objects then filter is the way and you just add a loop for the queryset itself:

     queryset = models_bdc.objects.filter(id_bdc='1')  # Assuming '1' is a valid id_bdc
    
     for instance in queryset:
            for i in range(1, 4): 
                ...