Django: Duplicated logic between properties and queryset annotations

后端 未结 5 989
我寻月下人不归
我寻月下人不归 2020-12-31 10:48

When I want to define my business logic, I\'m struggling finding the right way to do this, because I often both need a property AND a custom queryset to get the same info. I

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 11:28

    To avoid any duplication, one option could be:

    • remove the property in the Model
    • use a custom Manager
    • override it's get_queryset() method:
    class PickupTimeSlotManager(models.Manager):
    
        def get_queryset(self):
            return super().get_queryset().annotate(
                db_nb_bookings=Count(
                    'order', filter=Q(order__status=Order.VALIDATED)
                )
            )
    
    from django.db import models
    from .managers import PickupTimeSlotManager
    
    class PickupTimeSlot(models.Model):
        ...
        # Add custom manager
        objects = PickupTimeSlotManager()
    

    advantage: the calculated properties is transparently added to any queryset; no further action is required to use it

    disadvantage: the computational overhead occurs even when the calculated property is not used

提交回复
热议问题