djangodjango-models

How to get fields names that were chosen with method "only()"?


For example, I have simple model:

class Person(models.Model):
    id = models.BigAutoField("id", primary_key=True)
    first_name = models.CharField(max_length=150)
    surname = models.CharField(max_length=150)
    age = models.IntegerField()

I use method only to choose fields I need:

queryset = Person.objects.all().only("first_name", "age")

How can I get fields names("first_name", "age") that were chosen?

I tried this:
queryset.query.get_loaded_field_names()

But I got this error:
AttributeError:'Query' object has no attribute 'get_loaded_field_names'


Solution

  • You can use the .get_select_mask() method of the .query object:

    queryset.query.get_select_mask()

    This will return a dictionary where the keys are field objects, so you can get the name of the fields with:

    [f.name for f in queryset.query.get_select_mask()]

    This is however not a good idea from a software engineering perspective: the entire idea is that .only(…) [Django-doc] and .defer(…) [Django-doc] are used in a transparent manner.