从Django查询中提取字段名和值,可以使用以下方法:
values()
方法获取查询结果的字典形式,其中包含字段名和值。from django.db.models import Model
class MyModel(Model):
field1 = ...
field2 = ...
queryset = MyModel.objects.all().values('field1', 'field2')
for item in queryset:
print(item['field1'], item['field2'])
annotate()
方法对查询结果进行聚合操作,并提取字段名和值。from django.db.models import Count, Model
class MyModel(Model):
field1 = ...
field2 = ...
queryset = MyModel.objects.annotate(count=Count('field1')).values('field1', 'count')
for item in queryset:
print(item['field1'], item['count'])
values_list()
方法获取查询结果的元组形式,其中包含字段名和值。from django.db.models import Model
class MyModel(Model):
field1 = ...
field2 = ...
queryset = MyModel.objects.all().values_list('field1', 'field2')
for item in queryset:
print(item[0], item[1])
defer()
方法排除不需要的字段,只提取需要的字段名和值。from django.db.models import Model
class MyModel(Model):
field1 = ...
field2 = ...
field3 = ...
queryset = MyModel.objects.all().defer('field3').values('field1', 'field2')
for item in queryset:
print(item['field1'], item['field2'])
only()
方法仅提取需要的字段名和值。from django.db.models import Model
class MyModel(Model):
field1 = ...
field2 = ...
field3 = ...
queryset = MyModel.objects.all().only('field1', 'field2').values('field1', 'field2')
for item in queryset:
print(item['field1'], item['field2'])
以上方法可以帮助您从Django查询中提取字段名和值。
领取专属 10元无门槛券
手把手带您无忧上云