在django中从数据库中获取多行?

时间:2021-12-19 01:50:18

I have to fetch multiple rows from database based on some condition. There may be one row in database for matching query or multiple rows. I can use get() for one row but it does not fetch multiple rows.

我必须根据某些条件从数据库中获取多行。数据库中可能有一行用于匹配查询或多行。我可以将get()用于一行,但它不会获取多行。

Here is my code:

这是我的代码:

value=table.objects.get(col_name=1) then i can access its data as value.col but as i said it gives me error if this query returns more then one row.

value = table.objects.get(col_name = 1)然后我可以将其数据作为value.col访问,但正如我所说,如果此查询返回多行,则会给出错误。

I have also tried filter() , value=table.objects.filter(col_name=1) but then i can't access its data as value.col.

我也尝试过filter(),value = table.objects.filter(col_name = 1),但后来我无法将其数据作为value.col访问。

So please suggest me some way how i can fetch multiple rows from database and access columns one by one of those rows.

所以请建议我如何从数据库中获取多行并逐个访问这些行。

Thanks !!

谢谢 !!

2 个解决方案

#1


1  

yes, you must iterate over items from queryset:

是的,您必须迭代来自queryset的项目:

for item in value:
    item.col

#2


1  

values = table.objects.filter(col_name=1)
for value in values.all():
    # Do something with value.col

#1


1  

yes, you must iterate over items from queryset:

是的,您必须迭代来自queryset的项目:

for item in value:
    item.col

#2


1  

values = table.objects.filter(col_name=1)
for value in values.all():
    # Do something with value.col