I use Django 1.11. Here are the models:

class UserPromoCode(models.Model): promo_code = models.ForeignKey(PromoCode, related_name="user_promo_code") class PromoCode(models.Model): code = models.CharField(max_length=20) 

You need to get this sample in one or two queries to the database:

 promocodes = PromoCode.objects.all() for p in promocodes: p.assigned_times = UserPromoCode.objects.filter(user_promo_code=p.code).count() 

The problem is that the PromoCode.code field is not unique; therefore, I cannot use the link and execute PromoCode.objects.annontate(assigned_times=Count('user_promo_code')) , which will be an analogue of such a sample:

 promocodes = PromoCode.objects.all() for p in promocodes: p.assigned_times = p.user_promo_code.count() 

I PromoCode.objects.annontate(assigned_times=Count(???)) it should be something like PromoCode.objects.annontate(assigned_times=Count(???)) .

  • And what is the actual question? Can you formulate the problem more specifically? - Mikhail Rebrov
  • It is impossible to get promo codes with a number of user codes in which the same code is obtained by a single request. It is clear that this will not work, but it can be so clearer (the code of each promo code should be substituted for the 'code'): PromoCode.objects.annontate (assigned_times = Count (UserCode.objects.filter (user_code = 'code')))) - Daniel Zaikin

1 answer 1

Found a way to do this:

 from django.db.models import OuterRef, Subquery from django.db.models.functions import Coalesce user_promo_codes = UserPromoCode.objects.filter(promo_code__code=OuterRef('code')).values('promo_code__code') user_promocode_counts = upks.annotate(c=Count('*')).values('c') PromoCode.objects.annotate(assigned_times=Coalesce(Subquery(user_promocode_counts), 0) 

Coalesce is used because user_promocode_counts where it should be 0 received None.