Search code examples
pythondjangoormelixirecto

Python Django equivelant of preloading in Elixir Ecto


So I am coming from Elixir and Phoenix Background now working in a Django project.

At this stage I am investigating the ORM part of Django and I have the following question

Assume a model like the following

class Shop(models.Model):
    name = models.TextField()

class Product(models.Model):
    name = models.TextField()
    shop = models.ForeignKey(Shop)

At this point in Ecto you can do something like the following

shop = Context.get_by_id(1)
shop = preload(shop, :products)

and the result would be

%Shop{
 name: "Some name",
 products: [
   %Product{},
   %Product{}
 ] 
}

Taking care of all the necceesary joing queries behind the scene is there any similar functionality when working with Django ?


Solution

  • You should be able to do it with select_related or prefetch_related in querysets

    In your case you can do:

    shop = Shop.objects.select_related('products').get(id=5)
    

    or

    shops = Shop.objects.prefetch_related('products').all()
    

    There is a difference between select_related and prefetch_related on when it performs the query in the docs.