i want to fetch value dynamically in django model
users = User.objects.all()
for user in users:
print(user.first_name) # works fine
# now how to make it dynamic
onefield = "first_name"
print(user.onefield) # come error
# and for list of field name
fieldnames= ["first_name","last_name","email"]
for i in fieldnames:
print(user.i) # any shortcut for all value
CodePudding user response:
If the dynamic fields you want to access are strings, then use getattr().
fieldname = "first_name"
print(getattr(user, fieldname))
CodePudding user response:
For the way you are doing in your question
fieldname = "first_name"
print(getattr(user, fieldname))
You can also use other ways to get the values, such as:
fields = User.objects.all().values('first_name')
print(fields)
This returns a QuerySet that returns dictionaries. You can also use more fields
fields = User.objects.all().values('id', 'first_name', 'last_name')
print(fields)
<QuerySet [{'id': 1, 'first_name': 'Barney', 'last_name': 'Stinson'}]>
For unpacking
>>> qs = User.objects.all()
>>> values = ['first_name', 'email']
>>> qs.values(*values)
If you just need one value use values_list with flat=True
fields = User.objects.all().values_list('first_name', flat=True)
This return a tuple with the value