Reputation: 423
Right now i'm reading about custom managers that you can use to add additional logic when doing a CRUD action like Create. You make a custom manager class and then initialize the objects
attribute of the table class with an instance of the custom manager class.
I've also read that you can also use the pre_save and post_save signals to add additional save logic to the save action. My question is: When should i use a custom manager class over signals and is the use of a custom manager slower then the default manager of the Model class?
Thank you
Upvotes: 0
Views: 276
Reputation: 8202
OK, here's one I wrote earlier. I've cut out a lot of irrelevant stufff, hoping all the essentials remain. You need to know there's a Foreign Key chain PRSBlock
-> PRS2
-> Jobline
-> Description
. Using this, all queries for PRSBlock.objects.filter(...
will return PRSBlock
objects with extra fields membrane_t
, substrate_t
and material
from the Description
found by following this chain. They're almost always needed in this context, unlike most of the other things along that chain. select_related
would be serious overkill.
class PRSBlock_Manager(models.Manager):
def get_queryset(self):
return super().get_queryset().annotate(
membrane_t = F('PRS__jobline__description__mt'),
substrate_t= F('PRS__jobline__description__ft'),
material = F('PRS__jobline__description__material')
)
class PRSblock( models.Model):
# override the default manager
objects=PRSBlock_Manager() # annotate always with description parametrs relevant to block LUTs
PRS = models.ForeignKey( PRS2, models.CASCADE, related_name='prs_blocks')
# and lots of other fields that aren't relevant
Upvotes: 1