views:

315

answers:

1

I have :

class Award(models.Model) :
    name = models.CharField(max_length=100, db_index=True)

class Alias(models.Model) :
    awards = models.ManyToManyField('Award', through='Achiever')

class Achiever(models.Model):
    award = models.ForeignKey(Award)
    alias = models.ForeignKey(Alias)
    count = models.IntegerField(default=1)

How can I have an Alias which has all its achiever_set and awards prepopulated?

>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("achiever_set__award").get().achiever_set.all()[0].award.name
u'Perma-Peddle'
>>> len(db.connection.queries)
3
>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("awards").get().awards.all()[0].name
u'Dwarfageddon (10 player)'
>>> len(db.connection.queries)
2

I'm going to need a lot of access to the award that an alias has already gotten (both the intermediate table and the awards themselves). How can I batch all of these?

A: 

Can you try to write more detailed about needed effect? Do you want to make simply three table join, or do you need to get correct paris from the Achiever table?

You can use additional methods based on ManyToMany and ForeignsKey relations.

bluszcz
I want to pass around an alias object, and then in other methods get the achievers and awards.
Paul Tarjan
So you want just get proper Awards for providden alias?If yes, why use select_related instead of simply:<pre>Achiever.objects.filter(alias = alias)</pre>and then add additional methods?
bluszcz
Because that would be a second call to the be. I first get the alias `alias = Alias.objects.get(id=123)`, then I want the achievers and awards like `for achiever in alias.achiever_set().all() : points += achiever.award.points * achiever.count`. I don't want the loop to be a ton of DB accesses.
Paul Tarjan