好吧,首先,如果你试图访问一个你应该使用的对象
get
而不是
filter
自从
得到
返回单个对象,而
滤波器
返回一个查询集。
instance = get_object_or_404(models_bdc, id_bdc='1') # Get single object or 404 if not found
至于循环,你可以使用Python动态访问Django模型实例的字段
getattr
在你的循环中发挥作用。以下是在您看来实现这一目标的方法:
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)
如果你试图为多个对象实现这一点,那么
滤波器
就是这样,你只需为它添加一个循环
queryset
自身:
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):
...