Django Custom models.Manager using Foreign Related

2019-08-21 05:32发布

问题:

I want the custom query manager function to be executed based on percentage rate provided by Client and return rate based on currency column in foreign Rate model. What will be the best way accessing foreign Rate model column currency values only referenced in Client Model?

models.py:

class Company(models.Model):
   name = ...
 def __str__(self):
         return self.name

class Rate(models.Model):
   company = models.ForeignKey(Company)
   currency = ...
   name = ...

 def __str__(self):
         return self.name + " " + self.currency

class ClientManager(models.Manager):
    def res_currency(self, percentage):
        """
        Returns a QuerySet of modified rates annotated with their rates from the given percentage. This can then be filtered.
        Usage:
            Client.objects.res_currency(percentage).filter(rate__lt=1000).count()
        """
          currency = Client.objects.select_related('base_rate').values('base_rate__currency')

        Expression = percentage * F(currency)

        return self.get_queryset()\
            .annotate(rate=Expression)

class Client(models.Model):
   name = ...
   company = models.ForeignKey(Company)
   base_rate = models.ForeignKey(Rate)
   objects = ClientManager()

 def __str__(self):
         return self.name