I’m trying to do something like this:
class A(models.Model):
members = models.ManyToManyField(B)
class B(models.Model):
pass
# not sure what the right query is here
results = A.objects.all().[members.extra(select={"extra_field": ...})?]
# I want to be able to write this using the result of my query:
for r in result:
for m in r.members:
print m.extra_field
Is it possible to populate this extra_field without creating a new query for every model B in members?
Until prefetching arrives in Django 1.4, this will get a little hairy. Hold onto your hat.
First, you need to be able to query over the table that links your two models. If you don’t want to explicitly define a through table, you can use an unmanaged model like so:
Once you have this you can take a deep breath, hold your nose and do something like the following:
It’s nasty, but it works. Keep in mind that if the A and B tables start to get big then you’re going to run into performance issues – Django objects take up a lot of memory and can be very slow to iterate over. If you end up filtering or chunking A you’ll have to add the appropriate filters to the AB and B queries as well.
If anyone has a cleaner/more efficient way of doing this, I’d love to know!