Search code examples
pythondjangodjango-querysetprefetch

How can I prefetch_related() everything related to an object?


I'm trying to export all data connected to an User instance to CSV file. In order to do so, I need to get it from the DB first. Using something like

data = SomeModel.objects.filter(owner=user)

on every model possible seems to be very inefficient, so I want to use prefetch_related(). My question is, is there any way to prefetch all different model's instances with FK pointing at my User, at once?


Solution

  • Actually, you don't need to "prefetch everything" in order to create a CSV file – or, anything else – and you really don't want to. Python's CSV support is of course designed to work "row by row," and that's what you want to do here: in a loop, read one row at a time from the database and write it one row at a time to the file.

    Remember that Django is lazy. Functions like filter() specify what the filtration is going to be, but things really don't start happening until you start to iterate over the actual collection. That's when Django will build the query, submit it to the SQL engine, and start retrieving the data that's returned ... one row at a time.

    Let the SQL engine, Python and the operating system take care of "efficiency." They're really good at that sort of thing.