Sunday, 18 August 2013

Django prefetch_related, prefetching instances of through module in manytomany relation

Django prefetch_related, prefetching instances of through module in
manytomany relation

I have some model classes which structures are as follows:
class Reaction(models.Model):
participants = models.ManyToManyField(Participant,
through=ReactionParticipant,
related_name='reactions')
category = models.ForeignKey(Category,
related_name='reactions')
name = models.CharField(max_length=200)
description = models.TextField(blank=True, null=True)
disabled = models.BooleanField(default=False)
def get_reactant(self):
rps = self.reactionparticipants.select_related()
.filter(disabled=False,
participant_type=u'reactant')
if rps.exists():
rp = rps[0]
participant = rp.participant.reactant_persian_name
return participant
class Participant(models.Model):
reactant_english_name = models.TextField(null=True, blank=True)
operational_group = models.ForeignKey(OperationalGroup,
related_name='participants')
disabled = models.BooleanField(default=False)
class ReactionParticipant(models.Model):
reaction = models.ForeignKey('Reaction',
related_name='reactionparticipants')
participant = models.ForeignKey('Participant',
related_name='reactionparticipants')
participant_type = models.CharField(choices=CHOICES, max_length=70)
disabled = models.BooleanField(default=False)
When rendering my view, i do sth like this :
reactions =
Reaction.objects.filter(**filter_kwargs).prefetch_related('reactionparticipants')
return render_to_response(... , {'reactions:reactions, ... } ,context ... )
And inside my templates, i do sth like :
<div class="table-col col-13">{{ reaction.get_reactant }}</div>
That call for every row, is resulting in 2 new database hits when
get_reactant is called, which is not really good.
I guess I've prefetched all through model instances where i say :
.filter(**filter_kwargs).prefetch_related('reactionparticipants')
Does this have to do anything with the filter i've made inside my
get_reactant def ? Any ideas how to remove these database hits ?
Thanks in advance
(Anyways, This is for saving thousands of chemical reactions which all
have at most 2 reactants and one product )

No comments:

Post a Comment