There is a certain model with a function called with an additional parameter.
class Product(models.Model): category = models.ForeignKey(Category, verbose_name=u'Группа') name = models.CharField(u'Название товара', max_length=128) price = models.DecimalField(u'Стоимость единицы, руб.', max_digits=10, decimal_places=2) brand = models.ManyToManyField(Brand, related_name='products') def __unicode__(self): return self.name def discounted_price(self, user=None): return float(self.price) * self.max_discount(user=user) / 100 def max_discount(self, user=None): brand_q = Q(content_type=ContentType.objects.get_for_model(Brand), object_id__in=self.brand.all().values('id')) category_q = Q(content_type=ContentType.objects.get_for_model(Category), object_id=self.category.id) product_q = Q(content_type=ContentType.objects.get_for_model(Product), object_id=self.id) attr_q = Q(content_type=ContentType.objects.get_for_model(Attributes), object_id__in=self.attributes.all().values('id')) if user: user_q = Q(content_type=ContentType.objects.get_for_model(User), object_id=user.id) else: user_q = Q(content_type=ContentType.objects.get_for_model(User), object_id=None) discounts = Discount.objects.filter(brand_q | category_q | user_q | product_q | attr_q, start_date__lte=timezone.now(), end_date__gt=timezone.now()).\ aggregate(max_discount=Max('discount')) # discounts = Discount.objects.filter(brand_q | category_q | user_q | product_q | attr_q, # start_date__lte=timezone.now()).\ # aggregate(max_discount=Max('discount')) return discounts['max_discount'] if discounts['max_discount'] else 0.0 class Discount(models.Model): start_date = models.DateField(auto_now_add=True) end_date = models.DateField(auto_now_add=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') discount = models.FloatField() def __unicode__(self): return '{} "{}": {}'.format(self.content_type.name, self.content_object, self.discount) How can I insert this function in the queryset. I would like something similar, but, clearly - it does not work.
Product.objects.all().annotate(discounted_price=discounted_price(user=user)).order_by('discounted_price')