0

I am trying to filter my admin choices in a foreign key field following the documentation.

My model is pretty simple:

class Page(models.Model):
    title = models.CharField(max_length=50, null=False, blank=False, default="Title")
    layout = models.ForeignKey(Layout, null=False) #This sets the layout for the current page

To achieve that i should do something like:

class PageAdmin(admin.ModelAdmin):

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "layout":
            kwargs["queryset"] = Template.objects.get_a_queryset()
        return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

It is working, but it is going through the function 3 times every time i access the page, giving a total of 5 querys(3 times plus 2 it has by default). It is passing 3 times the same db_field.

How can i reduce that to only 1 query? Is this an intended behaviour and if so...why?

cdvv7788
  • 2,021
  • 1
  • 18
  • 26

1 Answers1

0

I'm not quite sure what is going on but I have two tools to point your way:

  1. IPython embed

    from IPython import embed
    ... lots of code ...
    embed()
    

The shell where you run your dev server will drop into IPython where you embed() so you can explore the stack

  1. traceback module

    import traceback
    ... lots of code ....
    traceback.print_stack()
    

This will print out the stack so you can differentiate the 3 invocations.