0

let's say i have the following fields

class ABC(models.Model)
    whatever=models.ManyToManyField('DEF')

class DEF(models.Model)
    something=models.CharField()

I want to retrieve ABC along side each DEF it's connected to, why i cannot do this ?

ABC.objects.filter(pk=123).select_related('DEF').get() 

I believe we can do this in one SQL query like so

select * from ABC inner join ABC_DEF on ABC.id = ABC_DEF.ABC_ID inner join 
DEF on DEF.id = ABC_DEF.DEF_ID

I know we can do prefetch but this will result in an extra query

  • It is a design decision, many relations can become inefficient for memory since you might load the _same_ object multiple times due to the joins. Whereas `prefetch_related` by performing the join on python side saves memory. – Abdul Aziz Barkat Jun 08 '21 at 13:26
  • Does this answer your question? [What's the difference between select\_related and prefetch\_related in Django ORM?](https://stackoverflow.com/questions/31237042/whats-the-difference-between-select-related-and-prefetch-related-in-django-orm) Although the title of the question is somewhat different, the answers do discuss the reasons for this. – Abdul Aziz Barkat Jun 08 '21 at 13:29

0 Answers0