[Django]-How do I retrieve a value of a field in a queryset object

7👍

You can use get instead of filter

obj = MainFile.objects.get(file_id='e3e978a3-0375-4bb9-85a2-5175e2ec097d')
obj.file_suffix

Use get when your queryset will fetch at most 1 row back from the database. In this case, since file_id is marked as the primary key, you can be certain that it is unique.

7👍

You can do this as a one-liner with simply:

MainFile.objects.values_list('file_suffix', flat=True).get(file_id='e3e978a3-0375-4bb9-85a2-5175e2ec097d')

the values_list queryset method retrieves only the column data that you need from the database. The get method then returns the single match to your filter.

Leave a comment