Dear group, I have two models in a foreign key relation. The 'master' table is extremely simple, having only the primary key field. The child table has multiple fields. (The rationale for the master table is that it has FK relations to a number of otherwise unrelated tables.)
My use case is that I have a bunch of child model objects, and I want to get their master model object. The naive code would be something like masters = [c.master for c in children] Since the foreign key is not null, we are ensured that c.master must exist. Moreover, there are no additional fields to query. So, the above should not need to result in a database call, as there is no new information to gather. Unfortunately, Django makes a (pretty silly) "select master.id from masters where master.id = X" call for each child object. Now there can easily be thousands of children, so this is not a trivial expense. I've tried various things like [Masters.objects.filter(pk=c.master_id).defer()[0] for c in children] But Django seems to insist on querying the primary key (which would normally make sense as an existence check, although it would be nice if this check could be deferred as well). Obviously, I could use [c.master_id for c in children] instead, but I hate passing integers around when I mean model objects (eg the model identity is lost). I guess in this case I could call the constructor directly (eg [Masters(id=c.master_id) for c in children]), but I think the assumption is that this would be a *new* object to be saved, so if other code would call m.save() it will try to insert the record. Is there a way to get the master model objects without invoking the database? If not, what is the preferred way to get the objects with a single query? list(Master.objects.filter(id__in=[c.master_id for c in all])) This call works, but is Django smart enough to break that into multiple queries if the list becomes too large to "fit" in a single query (I think most DB backends have some sort of limit on query length...) Thanks a lot, Wouter -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.