Are there "N + 1 problems" in "formfield_for_foreignkey()" in inline? (Django)

Viewed 70

I overrided formfield_for_foreignkey() in inline to display the combination text of "foreign key value" and "its parent value" to Django Admin as shown below:

# "admin.py"

class MyModelInline(admin.TabularInline):
    model = MyModel

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        formfield = super().formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == "my_field":
            formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})'
        return formfield

Then, with "print()", I checked how many time "formfield_for_foreignkey()" and "if block" in "formfield_for_foreignkey()" are called as shown below when opening the page:

# "admin.py"

class MyModelInline(admin.TabularInline):
    model = MyModel

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        formfield = super().formfield_for_foreignkey(db_field, request, **kwargs)
        
        print("formfield_for_foreignkey") # Called "3 times"

        if db_field.name == "my_field":

            print("if block") # Called "3 times"

            formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})'
        return formfield

As a result, print("formfield_for_foreignkey") is called 3 times which means "formfield_for_foreignkey()" is called 3 times.

And, print("if block") is called 3 times which means "if block" in "formfield_for_foreignkey()" is called 3 times.

My questions:

Is it "N + 1 problem" that:

  • "formfield_for_foreignkey()" itself is called 3 times?
  • "if block" itself is called 3 times?
  • "{obj}" in "if block" is called 3 times?
  • "{obj.my_parent}" in "if block" is called 3 times?
0 Answers
Related